makefile中未定义的引用

时间:2011-11-25 20:23:14

标签: c++ linux makefile g++

好的,我已经阅读了大约10个教程,但我一直都会遇到错误,我有5个文件,main.cpp class.cpp,class.h和functions.cpp以及functions.h。所有这些都使用来自不同对象的函数,这意味着functions.cpp中的函数使用来自classes.cpp的对象。

我的makefile如下所示

CC = g++ -O2 -I./sdl/include -L.
LIBS = -lm -lSDL -lpthread -ldl
SRC = main.cpp
SDLF = SDLfunctions.cpp
CLASS = classes.cpp
CLASSH = classes.h
SDLFH = SDLfunctions.h

all: main

main: SDLfunctions.o Classes.o $(SRC)
    $(CC) -o $@ $(SRC) $(LIBS)

SDLfunctions.o: $(SDLFH) $(SDLF) $(CLASS) $(CLASSH)
    $(CC) -o $@ $(SDLF) $(LIBS)

Classes.o: $(CLASS) $(CLASSH) $(SDLF) $(SDLFH)
    $(CC) -o $@ $(CLASS) $(LIBS) 

我一直告诉我它有未定义的引用。我错过了什么?

makefile输出

/usr/lib/i386-linux-gnu/gcc/i686-linux-gnu/4.5.2/../../../crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
/tmp/ccJG6yQA.o: In function `DrawEnemies(SDL_Surface*)':
SDLfunctions.cpp:(.text+0x3a7): undefined reference to `Enemy::sprite'
/tmp/ccJG6yQA.o: In function `rysujpociski(int, SDL_Surface*, SDL_Surface*, 
std::vector<AllyBullet, std::allocator<AllyBullet> >&, double)':
SDLfunctions.cpp:(.text+0x141f): undefined reference to `AllyBullet::sprite'
/tmp/ccJG6yQA.o: In function `global constructors keyed to width':
SDLfunctions.cpp:(.text+0x14a7): undefined reference to `Enemy::Enemy()'
collect2: ld returned 1 exit status
make: *** [SDLfunctions.o] Error 1

当我在Visual C ++中使用它们时,文件编译得很好,所以它必须是我的makefile。

3 个答案:

答案 0 :(得分:7)

你确实在做一些奇怪的事情。你应该编译(-c)目标文件,然后将它们链接在一起。这看起来像这样:

CC = g++ -O2 -I./sdl/include -L.
LIBS = -lm -lSDL -lpthread -ldl
SRC = main.cpp
SDLF = SDLfunctions.cpp
CLASS = classes.cpp
CLASSH = classes.h
SDLFH = SDLfunctions.h

all: main

main: SDLfunctions.o Classes.o $(SRC)
    $(CC) -o $@ $(SRC) SDLfunctions.o Classes.o $(LIBS)  # you forgot to link
                                                         # the object files

SDLfunctions.o: $(SDLFH) $(SDLF) $(CLASS) $(CLASSH)
    $(CC) -o $@ -c $(SDLF)        # -c added to compile, not link

Classes.o: $(CLASS) $(CLASSH) $(SDLF) $(SDLFH)
    $(CC) -o $@ -c $(CLASS)       # -c added to compile, not link

当你这样做时,如果你单独编译main.o也会更好。因此:

CC = g++ -O2 -I./sdl/include -L.
LIBS = -lm -lSDL -lpthread -ldl
MAIN = main.cpp
SDLF = SDLfunctions.cpp
CLASS = classes.cpp
CLASSH = classes.h
SDLFH = SDLfunctions.h

all: main

main: SDLfunctions.o Classes.o main.o
    $(CC) -o $@ SDLfunctions.o Classes.o main.o $(LIBS)

main.o: $(SDLFH) $(MAIN) $(CLASSH)
    $(CC) -o $@ -c $(MAIN)

SDLfunctions.o: $(SDLFH) $(SDLF) $(CLASS) $(CLASSH)
    $(CC) -o $@ -c $(SDLF)

Classes.o: $(CLASS) $(CLASSH) $(SDLF) $(SDLFH)
    $(CC) -o $@ -c $(CLASS)

另请注意,我在使用$(LIBS)时删除了-c,因为当时不会发生链接。

答案 1 :(得分:6)

您正在尝试将.o文件链接到可执行文件中。将-c添加到编译标志中,以便仅针对您的目标文件进行编译。

将它作为第一个选项

SDLfunctions.o: $(SDLFH) $(SDLF) $(CLASS) $(CLASSH)
    $(CC) -c -o $@ $(SDLF) $(LIBS)

答案 2 :(得分:2)

你有一个错字。您使用的是$(CLASSESH),但声明为CLASSH