Include source file in C program
How do I include the function foo () foo.c in this little program (sorry for my noob question):
In the foo.h file:
/* foo.h */
#include <stdio.h>
#include <stdlib.h>
int foo(double largeur);
In foo.c:
/* foo.c */
#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
int foo(double largeur)
{
printf("foo");
return 0;
}
And in main.c:
/* main.c */
#include <stdio.h>
#include <stdlib.h>
#include "foo.h"
int main(int argc, char *argv[])
{
printf("Avant...");
foo(2);
printf("Apres...");
return 0;
}
After compilation:
$ gcc -Wall -o main main.c
I am getting this error:
Undefined chars: "_foo", ref: _main in ccerSyBF.o ld: character not found collect2: ld returned 1 exit status
Thanks for any help.
source to share
Writing a C program requires two steps, compilation and linking. To just run the compilation part, use the option -c
for gcc
:
gcc -c main.c
This creates an object file, main.o
(or main.obj
on Windows). Likewise for gcc -c foo.c
. At this point, you will not receive the above error message. Then you link the two object files together. At this point, the symbol is foo
allowed. The reason you got the error was because the linker couldn't find the symbol because it was only looking at main.o
and not at foo.o
. The compiler is usually started with gcc
, so to link your object files and create the final executable main
use
gcc -o main main.o foo.o
You can also do this in your MakeFiles, for example:
APP_NAME = Foo
Foo_HEADERS = foo.h
Foo_FILES = main.c foo.c
If you are not that familiar with MakeFiles, I suggest you take a look at the Make Docs , but this is a simple example, APP_NAME
sets the name of the compiled executable (in this case, it is Foo), Foo_HEADERS
will set the headers used by your application, Foo_FILES
you install the source files of your applications. don't forget to put APP_NAME
(in this case Foo) at the beginning _HEADERS
and _FILES
. I suggest you use MakeFiles because they will organize your application build process and will be better for the end user.
source to share