Why does CC not see my function definition in header?
I'm writing a simple application in ANSI C. I am using GCC in a Unix environment.开发者_C百科
I have the following sample application:
    //main.c
#include "foo.h"
int main()
{
int result;
result = add(1,5);
return0;
}
Header:
  //foo.h
    #ifndef FOO_H_INCLUDED
    #define FF_H_INCLUDED
    int add(int a, int b);
    #endif
Implementation:
//foo.c
int add(int a, int b)
{
return a+b;
}
I am compiling my program with the following command:
 cc main.c -o main.o
The compiler complains that 'reference to add is undefined'. Is this a linking problem? How do properly make use of my header?
Thanks!
You need to compile both your source files together:
cc main.c foo.c -o main
Also, in this case, -o produces an executable, so calling it main.o can be misleading.
Yet another tidbit, though unrelated to the question: the #ifndef and #define in foo.h don't match.
The header is not your current problem. Your current problem is that you're not compiling the add function definition in foo.c.
Try
cc main.c foo.c -o main.o
If you are trying to compile main.c into an assembled object file, you need to prevent gcc from trying to link. This is done via
cc -c main.c -o main.o
You can compile all other object files, then when you have all of your object files ready, you simply do
cc main.o obj1.o anotherOBJ.o -o myExecutableBinary
"undefined reference" is a linker error, not a compiler error.
The compiler sees the declaration in the header, but you have not compiled or linked the definition in foo.c. Your title uses the term definition incorrectly.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论