User
User

Reputation: 24731

How to include helper functions in C?

There are 4 files:

helper.h //contains the signatures of functions in helper.c
helper.c //implements the signatures in helper.h
file.h //has all the includes needed to run file.h
file.c //this file includes file.h and helper.h

In file.c, I need to use the function that is defined in helper.c in my main function. However, file.c is saying that there is an undefined reference to 'func_found_in_helper.c'

Is this structure correct?

Upvotes: 2

Views: 18400

Answers (2)

abligh
abligh

Reputation: 25119

Yes, provided file.c contains

#include "helper.h"

and when building your program you link together helper.o and file.o.

You also need to ensure you compile each of the files with -c so that the compiler only compiles (and not links); do the link later with all the object files.

Here's a working example (I don't actually need a main.h but if you have one of those, #include it from main.c):

main.c

#include <stdio.h>
#include <stdlib.h>
#include "helper.h"

int
main (int argc, char **argv)
{
  test ();
  exit (0);
}

helper.c

#include <stdio.h>

void
test ()
{
  printf ("Hello world\n");
}

helper.h

void test ();

To compile

gcc -Wall -Werror -c -o main.o main.c
gcc -Wall -Werror -c -o helper.o helper.c

To link

gcc -Wall -Werror -o test main.o helper.o

In a Makefile

test: main.o helper.o
    gcc -Wall -Werror -o test main.o helper.o

%.o: %.c
    gcc -c -Wall -Werror -o $@ $<

clean:
    rm -f *.o test

To run

$ ./test
Hello world

It's a bit difficult to tell what else might be wrong without the program; my guess is you simply forgot the -c flag to gcc, or forgot to link in helper.o.

Upvotes: 5

undefined reference to 'func_found_in_helper.c'

That's a little odd, as it suggests you have tried to call the function using the '.c' extension, rather than just the function name. Maybe the '.' is just a typo in the question ?

Also a linker will flag an undefined symbol, so it may also be that you have not told the linker where to find helper.o ( the helper.c file compiled to the an object file ). The compiler will start the linker automatically. Did you compile helper.c first ?

Upvotes: 1

Related Questions