(.text+0x20): undefined reference to `main' and undefined reference to function
This rule
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
is wrong. It says to create a file named producer.o (with -o producer.o
), but you want to create a file named main
. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
As Shahbaz rightly points out, the gmake professionals would also use $^
which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ $^
This error means that, while linking, compiler is not able to find the definition of main()
function anywhere.
In your makefile, the main
rule will expand to something like this.
main: producer.o consumer.o AddRemove.o
gcc -pthread -Wall -o producer.o consumer.o AddRemove.o
As per the gcc
manual page, the use of -o
switch is as below
-o file Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If
-o
is not specified, the default is to put an executable file ina.out
.
It means, gcc will put the output in the filename provided immediate next to -o
switch. So, here instead of linking all the .o
files together and creating the binary [main
, in your case], its creating the binary as producer.o
, linking the other .o
files. Please correct that.