Question

EDITS: Including link to my makefile

I have a main program that calls a bunch of functions defined in other source files. This is not a problem because I am using cc -c functionSource.c functionHeader.h and generating object files before compiling my main program with cc main.c func1.o func2.o .... -o test.o

I am having problems when one of my functions depends on another function. For example: My main program calls an shuffle function which is defined in it's own source file and the shuffle function calls a swap function which in turn is defined in it's own source file.

When i try to generate the shuffle.o file for my main program using cc -c shuffle.o I get an undefined reference to swap error.

When I try to cc shuffle.c swap.o i get an undefined reference to main error.

Here is my makefile

How do I go about fixing this? Found the problem. I had a swap function declared inside insertionSort.h and shuffle.h but no implementations.

Was it helpful?

Solution

Have a look to the man page: '-c' makes the compiler generating object files only (not trying to link).

Do the following:

cc -c insertionSort.c     # => gives insertionSort.o
cc -c -c functionSource.c # => gives functionSource.o
cc insertionSort.o functionSource.o ...and-so-on... main.c -o test 

It's not necessary to specify header files - it doesn't help.

BTW: If you have mor than one implementation file, it is rather useful

  • (a) to learn make
  • (b) stick to the convention that object files and programs should be named like th sources.

E.g:

foo.c => foo.o
bar.c => bar

etc - you get the picture.

OTHER TIPS

This has nothing to do with make. You need to get a book on introductory C programming, that will explain how to use the preprocessor, and you need to examine the documentation for your compiler so you understand what the different compiler flags do (such as when you want to use the -c flag and when you don't, and what the difference is).

It's wrong to include header files (.h files) on the compile line. Only source files (.c) should be included on the command line when building object (.o) files. You should be adding the headers you need into your .c files using the #include directive: #include "insertionSort.h". If you're missing a reference to a function, then #include the header file that declares that function: #include "swap.h".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top