开发者

Include a source file in a C program

开发者 https://www.devze.com 2022-12-09 17:52 出处:网络
How can I include foo() function of foo.c in this small program (sorry for my noob question): In my foo.h file:

How can I include foo() function of foo.c in this small program (sorry for my noob question):

In my 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)
{
 开发者_如何学JAVA 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 compiling:

$ gcc -Wall -o main main.c

I get this error:

Undefined symbols: "_foo", referenced from: _main in ccerSyBF.o ld: symbol(s) not found collect2: ld returned 1 exit status

Thanks for any help.


$ gcc -Wall -o main main.c foo.c

GCC doesn't know to look for foo.c if you don't tell it to :)


Creating a program in C requires two steps, compiling and linking. To just run the compiling part, use the -c option to gcc:

 gcc -c main.c

This creates an object file, main.o (or main.obj on Windows). Similarly for gcc -c foo.c. You won't get the error message above at this stage. Then you link these two object files together. At this stage, the symbol foo is resolved. The reason you got the error message was because the linker couldn't find the symbol, because it was only looking at main.o and not foo.o. The linker is usually run from gcc, so to link your object files and create the final executable file main, use

 gcc -o main main.o foo.o


You have to compile foo.c also because it is another module. Let me see how they do it in gcc:

$ gcc -Wall main.c foo.c -o main 


You could also do this in your MakeFiles, like this:

APP_NAME = Foo
Foo_HEADERS = foo.h
Foo_FILES = main.c foo.c

If you're not so much familiar with MakeFiles i suggest you to take a look at Make Docs, but this is a simple example, APP_NAME sets the name of the compiled executable(in this case is Foo), Foo_HEADERS will set the headers used by your application, Foo_FILES you will set the source files of your applications, remember to put the APP_NAME(in this case Foo) at the beginning of _HEADERS and _FILES. I suggest you to use MakeFiles because they will organize you application build process and will be better for the end-user.

0

精彩评论

暂无评论...
验证码 换一张
取 消