Undefined reference to 'main' error in crt1.o function _start
Solution 1
Here are a couple of hints:
-o $@ $<
is not needed for .o files, so remove that from those targets.-Wall
makes more sense when used while compiling not linking. So I would add it to theCC
andCXX
line instead (or better, to theCFLAGS
andCXXFLAGS
).- the clean target should be a dependency of the
.PHONY
target, so that you can execute it always (without previous check for changed dependencies).
If you still get an error about missing references to your functions from modules.c, you are probably missing some extern "C" ...
statements in main.cpp. That's because the internal name of C++ functions is calculated differently than that from C functions (i think C++ prefixes all names with the namespace, class names, etc). To tell C++ that a specific function can be found using the old internal name for linkage, use the extern "C" statement.
Solution 2
Use $^ instead of $<. The latter contains only the first dependency (modules.o), so main.o is not linked into the executable.
Rayne
Updated on May 31, 2020Comments
-
Rayne almost 4 years
I've having problems with my Makefile.
I'm trying to create a program from 2 files - main.cpp that contains the main function, and modules.c that contains the definitions of the functions that are called in main(). modules.c only contain function definitions, no main function.
My Makefile is as follows:
CC := gcc CXX := g++ LINK := g++ -Wall CFLAGS := -g CXXFLAGS := -g TARGET = program $(TARGET): modules.o main.o $(LINK) -o $@ $< -lpcap clean: rm *.o $(TARGET) modules.o: $(CC) $(CFLAGS) -c modules.c -o $@ $< main.o: $(CXX) $(CXXFLAGS) -c main.cpp -o $@ $<
I have included "modules.h", which contains all the function declarations, in my main.cpp. The CFLAGS and CXXFLAGS variables point to the correct paths containing
When I try to make using this Makefile, I get the error
/usr/lib/gcc/x86_64-redhat-linux/4.4.4/../../../../lib64/crt1.o: In function '_start':
(.text+0x20): undefined reference to 'main'If I switch the order of modules.o and main.o in my $(TARGET) line, then I get errors that say "undefined reference to" the functions I have defined in modules.c, in main.cpp.
I don't know what is wrong.
Thank you.
Regards, Rayne
-
Rayne about 13 yearsThis solved the "undefined reference to main" problem. But now I get the "undefined reference to" the functions I have defined in modules.c, in main.cpp error. In my main.cpp, I have included modules.h, and declared the functions in modules.c as extern functions.
-
Patrick Georgi about 13 yearsTry compiling the C code with g++, too (if only for testing). C++ has some interesting name mangling rules which might collide here. If that fixes it, look into 'extern "C"'