Accelerated C ++:在第4章中编译程序

时间:2015-02-19 04:22:30

标签: c++ c++11 makefile

我编写了一个Makefile来编译文件并输出文件“main”,我最终将通过“./main”执行。下面是我的Makefile:

CXX=clang++
CXXFLAGS=-g -std=c++11 -Wall -pedantic
BIN=prog

SRC=$(wildcard *.cpp)
OBJ=$(SRC:%.cpp=%.o)

all: Student_info median grade main

main: main.cpp
    $(CXX) $(CXXFLAGS) main.cpp -o main grade.o median.o Student_info.o

grade: grade.h grade.cpp
    $(CXX) $(CXXFLAGS) grade.cpp -o grade.o

median: median.h median.cpp
    $(CXX) $(CXXFLAGS) median.cpp -o median.o

Student_info: Student_info.h Student_info.cpp
    $(CXX) $(CXXFLAGS) Student_info.cpp -o Student_info.o

clean:
    rm -f *.o
    rm -f main

然而,它说

clang++ -g -std=c++11 -Wall -pedantic Student_info.cpp -o Student_info.o
Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [Student_info] Error 1

我的Makefile出了什么问题?

1 个答案:

答案 0 :(得分:2)

Student_info: Student_info.h Student_info.cpp
    $(CXX) $(CXXFLAGS) Student_info.cpp -o Student_info.o

看起来您希望将其编译为目标文件 - 无需链接。为此,您需要传递-c。此外,目标的名称应为Student_info.o

Student_info.o: Student_info.h Student_info.cpp
    $(CXX) $(CXXFLAGS) -c Student_info.cpp -o Student_info.o

同样适用于grademedian

main不仅取决于main.cpp,还取决于您链接的目标文件:

main: main.cpp Student_info.o grade.o median.o
    $(CXX) $(CXXFLAGS) main.cpp -o main grade.o median.o Student_info.o