Reputation: 3
I'm struggling to create a makefile for two executables
I want to be able to create a makefile that builds everything and then executes exec1 and exec2
I've got the following files with the headers included
array.c: array.h const.h
exec1.c: exec1.h array.h
exec2.c: exec2.h array.h
What I currently have for my makefile is:
MAINS = exec1 exec2
OFILES = exec1.o exec2.o
all: $(MAINS)
$(MAINS): %: %.o array.h const.h
gcc -o $@ $^
$(OFILES): %.o: %.c %.h array.h const.h
gcc -c %.c
array.o: %.c const.h
gcc -c %.c
But it's not working. It says there's undefined references to some of the functions defined in array.h
Upvotes: 0
Views: 73
Reputation: 223689
Your makefile format won't work like that. Try this instead:
MAINS = exec1 exec2
all: $(MAINS)
# define source dependencies for each object file
exec1.o: exec1.c exec1.h array.h
exec2.o: exec2.c exec2.h array.h
array.o: array.c array.h const.h
# build for exec1 with object file dependencies
# $@ = the target to build
# $^ = the dependencies
exec1: exec1.o array.o
gcc -o $@ $^
# build for exec2 with object file dependencies
exec2: exec2.o array.o
gcc -o $@ $^
# generic build for object files
# $< = the source filename matching the object file
%.o: %.c
gcc -c $<
clean:
rm -f exec1 exec2 exec1.o exec2.o array.o
Upvotes: 0
Reputation: 479
Question is a bit unclear on what the error here is, but I will try to guess. "Undefined reference" is not a Makefile issue, but rather is an issue when using GCC. We cannot see the code, but generally this means you referred to a function or variable that the compiler/linker cannot find. When linking, be sure to link all object files together:
gcc -o outputfile obj1.o obj2.o
Be sure to include function prototypes of all functions used outside of the original source file:
main.c:
#include"foo.h"
int main(void)
{
foo();
return 0;
}
foo.c:
void foo()
{
/*implementation*/
}
foo.h:
void foo();
Compile:
gcc -c foo.c -o foo.o
gcc -c main.c -o main.o
gcc main.o foo.o -o MyProgram
Upvotes: 1