tags:

views:

64

answers:

4

Hello..

I'm writing a simple application in ANSI C. I am using GCC in a Unix environment.

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!

+6  A: 

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.

casablanca
And a second tidbit - while not strictly necessary, it would be a good idea to put a `#include "foo.h"` into `foo.c` to ensure that the function definition of `add()` in `foo.c` matches up with the declaration that everyone sees.
Michael Burr
@Michael Burr: Oh yes, that too.
casablanca
Awesome! So do you generally start by creating a makefile? I can see how the list of source files could get large fast.
Nick
@Nick: Indeed, that's exactly why makefiles were invented.
casablanca
@Nick: Or spare yourself the pain and use an IDE that will generate the makefile (and critiaclly all the dependencies) for you (or its equivalent). For most projects that will suffice.
Clifford
@Clifford Is there a good IDE for C that you can recommend? I have used Geany.
Nick
@Nick: I have no great experience of Unix IDE possibilities, but perhaps Eclipse with CDT or K-Develop.
Clifford
+1  A: 

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
pmg
A: 

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
Kizaru
A: 

"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.

Clifford