对Makefile.win中函数的未定义引用

Undefined reference to functions in Makefile.win

本文关键字:未定义 引用 函数 Makefile win      更新时间:2023-10-16

我最近在做一个uni项目。一切都很好,直到我为代码添加了一些收尾工作。当我尝试编译时,我得到:

main.cpp:(.text+0x1f6): undefined reference to 'readline(std::vector<std::string,std::allocator<std::string> >&, int)'
main.cpp:(.text+0x35d): undefined reference to 'readword(std::vector<std::string, std::allocator<std::string> >&, int)'

我的项目由3个文件组成:main.cpp、read.h和read.cpp。以下是makefile中编译器似乎有问题的行:

$(BIN): $(OBJ)
$(CPP) $(LINKOBJ) -o $(BIN) $(LIBS)
main.o: main.cpp
$(CPP) -c main.cpp -o main.o $(CXXFLAGS)
read.o: read.cpp
$(CPP) -c read.cpp -o read.o $(CXXFLAGS)

如果能给我任何帮助,我将不胜感激。

假定read.cpp包含链接器找不到的两个函数的定义。所以你需要两个对象来构建你的二进制文件:

$(BIN) : read.o main.o
    $(CPP) read.o main.o -o $(BIN)

此外,您还可以使用一些常见的技巧来简化makefile。由于您构建的所有对象文件都是相同的,因此您可以制定一条规则:

# rule for all .o files depends their specific .cpp
%.o : %.cpp
    # here $< refers to the "%.cpp" dependency, and "$@" is the target
    $(CPP) -c $< -o $@ $(CXXFLAGS)

这将编写您的main.oread.o规则。然后,我们只需要告诉make,这就是我们想要的:

SRC = read.cpp main.cpp
OBJ = $(patsubst %.cpp,%.o,$(SRC)) ## OBJ is "read.o main.o"
$(BIN) : $(OBJ) # depends on all the object files
     $(CPP) $(OBJ) -o $(BIN)

现在,如果添加write.cpp,则只需修改makefile中的一行,而不必修改多行。然后,你甚至可以避免这样做:

SRC = $(wildcard *.cpp)