链接对象与依赖项

时间:2012-03-01 18:28:36

标签: c++ linker g++

我的项目树:

./main.h
./main.cpp
./Makefile
./sources/myclass.cpp
./includes/myclass.h
./objects/

#./Makefile
BUILD = myexecutable

LDFLAGS = -lsfml-graphics -lsfml-window -lsfml-audio -lsfml-system
CXXFLAGS = -Wall
RM = rm -rf

OBJECTS =  main.o $(addprefix $(OBJ_DIR), myclass.o)

OBJ_DIR = objects/
SRC_DIR = sources/

.PHONY: clean

all: clean $(BUILD)

$(BUILD): $(OBJECTS)
    $(CXX) $(LDFLAGS) -o $(BUILD) $(OBJECTS)

$(OBJ_DIR)%.o: $(SRC_DIR)%.cpp
    $(CXX) -MM $(CXXFLAGS) -c $< > $(OBJ_DIR)$*.d # New line for create myclass.d
    $(CXX) $(CXXFLAGS) -c $< -o $@


clean:
    $(RM) $(BUILD) $(OBJ_DIR)*.o

当我尝试运行make时,我得到了这个:

$ make
rm -rf myexecutable objects/*.o
g++ -MMD -Wall -c sources/myclass.cpp -o objects/myclass.o
g++ -lsfml-graphics -lsfml-window -lsfml-audio  -lsfml-system -o myexecutable main.o objects/myclass.o
main.o: In function `main':
main.cpp:(.text+0x176): undefined reference to `mynamespace::MyClass::method()'
main.cpp:(.text+0x185): undefined reference to `mynamespace::MyClass::otherMethod()'
main.cpp:(.text+0x406): undefined reference to `mynamespace::MyClass::~MyClass()'
main.cpp:(.text+0x50e): undefined reference to `mynamespace::MyClass::~MyClass()'
collect2: ld devolvió el estado de salida 1
make: *** [myexecutable] Error 1

如何修复myclass.o的main.o依赖关系?

修改

我为create * .d依赖* .d文件添加了一个新行,我不知道如何使用

1 个答案:

答案 0 :(得分:0)

纠正于:

LIBES = -lsfml-graphics -lsfml-window -lsfml-audio -lsfml-system
$(BUILD): $(OBJECTS)
     $(CXX) -o $(BUILD) $(OBJECTS) $(LIBES)

LIBES应该替换LDFLAGS,并且应更改BUILD的两行。

链接顺序非常重要:放置目标文件,然后将库从高级系统库放到最低级别的系统库。