Knowledge Base Article

How do I include a C file in my Nios II C software project?

Description

C2H doesn’t support generating accelerators from C files. 

 

There is a work-around which will enable you to call your accelerator(s) from a C program which involves moving the functions you wish to accelerate from a C source file to a C source file.  Once your functions are in a C source file, the C2H compiler can effectively “see them” and convert them into hardware accelerators. 

 

There are some additional steps necessary for mixing C and C functions (and files).

 

The GNU tool-chain supports the calling of C functions from C programs (and vice versa) through a well defined methodology of explicit assertion.   The way this works is that, from your C program you tell the compiler which functions should be call as C functions- instead of C .  This operation is done through the use of the extern “C” syntax within the C source file.

 

Some examples of the extern “C” syntax in action are as follows:

  1. Calling C function from C program

Setup:  You have a function void bar(void), which lives in C source file “bar.c” that you want to call from the C source file “foo.cpp”.

Solution:  Add this to the top of “foo.cpp”-  

                extern “C”void foo(void);

 

  1. Calling C functions from C program

Setup:  A collection of functions which lives in C source file “bar.c” that you want to call from the C source file “foo.cpp”.

Solution:  Simply add braces around the group of functions at the top of the extern statement in “foo.cpp”-  

                extern “C” {

void foo(void);

int foo2(int number);

int foo3(int number1, int number2);

}

 

  1. Calling a C header from a C program

Setup: You have a whole collection of C functions (or a library) in a file called “bar.c” that you want to call from your C program “foo.c”, and you really don’t want to list them individually through procedure #2 (above).  You do have a header file for “bar.c” called “bar.h” which declares the interface to the functions.

Solution: The extern statement also works for header files… In the file “foo.cpp”, use the extern statement to add the header file-

                extern “C” {

                                #include “bar.h”

}

 

 

Which methodology is best to use with C2H?  When using the C2H compiler, it is recommended that a user “isolate” the function for acceleration into its own file, so using the first example is the best approach for accelerating functions with the C2H compiler.

 

Updated 6 days ago
Version 3.0
No CommentsBe the first to comment