Rayne
Rayne

Reputation: 14977

Undefined reference to 'main' error in crt1.o function _start

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

Upvotes: 4

Views: 30887

Answers (2)

tux21b
tux21b

Reputation: 94699

Here are a couple of hints:

  1. -o $@ $< is not needed for .o files, so remove that from those targets.
  2. -Wall makes more sense when used while compiling not linking. So I would add it to the CC and CXX line instead (or better, to the CFLAGS and CXXFLAGS).
  3. 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.

Upvotes: 2

Patrick Georgi
Patrick Georgi

Reputation: 698

Use $^ instead of $<. The latter contains only the first dependency (modules.o), so main.o is not linked into the executable.

Upvotes: 8

Related Questions