使用 c++ 生成文件的文件链接
File linking with c++ makefile
>Make file:
INCLUDE = -I/usr/X11R6/include/
LIBDIR = -L/usr/X11R6/lib
COMPILERFLAGS = -Wall
CC = g++
CFLAGS = $(COMPILERFLAGS) $(INCLUDE)
LIBRARIES = -lX11 -lXi -lXmu -lglut -lGL -lGLU -lm
All: project
project: main.o landscape.o point.o
$(CC) $(CFLAGS) -o $@ $(LIBDIR) $< $(LIBRARIES)
clean:
rm *.o
我有一个横向.cpp、landscape.h、point.cpp、point.h 和 main.cpp 文件我在我的主文件中包含"point.h".cpp我得到:
g++ -Wall -I/usr/X11R6/include/-o project -L/usr/X11R6/lib main.cpp -lX11 -lXi -lXmu -lglut -lGL -lGLU -lm/tmp/ccdpJ8HH.o: In function main':
main.cpp:(.text+0x1c0): undefined reference to
Point::P oint(int, int('collect2:错误:ld 返回 1 个退出状态生成文件:15:目标"项目"的配方失败make: *** [project] 错误 1
project: main.o landscape.o point.o
$(CC) $(CFLAGS) -o $@ $(LIBDIR) $< $(LIBRARIES)
在这里,您需要链接所有.o文件。您在此处的规则将仅使用 main.o 文件。因为$<
只是第一个依赖项。 $^
应该适用于所有三个。所以试试:
project: main.o landscape.o point.o
$(CC) $(CFLAGS) -o $@ $(LIBDIR) $^ $(LIBRARIES)
我建议你使用更完整的Makefile。
另外,使用 CXX=g++
和 CXXFLAGS
而不是 CC
和 CFLAGS
,因为您正在编译C++并且make
有特殊的变量。
这是我可以使用的Makefile示例。
# Project name
NAME= project
# Include directory
INC_DIR= /usr/X11R6/include/
# Library directory
LIB_DIR= /usr/X11R6/lib/
# Compiler
CXX= g++
# Source files
SRC_DIR= # in case your cpp files are in a folder like src/
SRC_FILES= main.c
landscape.c
point.c
# Obj files
OBJ= $($(addprefix $(SRC_DIR), $(SRC_FILES)):.c=.o)
# that rule is composed of two steps
# addprefix, which add the content of SRC_DIR in front of every
# word of SRC_FILES
# And a second rule which change every ".c" extension into ".o"
LIBS= X11
Xi
Xmu
glut
GL
GLU
m
# Compilation flags
CXXFLAGS= -Wall
CXXFLAGS+= $(addprefix -I, $(INC_DIR))
LDFLAGS= $(addprefix -L, $(LIB_DIR))
$(addprefix -l, $(LIBS))
# Rules
# this rule is only linking, no CFLAGS required
$(NAME): $(OBJ) # this force the Makefile to create the .o files
$(CXX) -o $(NAME) $(OBJ) $(LDFLAGS)
All: $(NAME)
# Remove all obj files
clean:
rm -f $(OBJ)
# Remove all obj files and the binary
fclean: clean
rm -f $(NAME)
# Remove all and recompile
re: fclean all
# Rule to compile every .c file into .o
%.o: %.c
$(CXX) -o $@ -c $< $(CFLAGS)
# Describe all the rules who do not directly create a file
.PHONY: All clean fclean re
我不确定它是否完美,但它更好。另外,不要忘记将项目规则放在All
规则之前,以避免在简单地调用make
时重新链接。
这样,您还可以添加漂亮的消息(例如在%.o: %.c
规则中(。
有了它,您只需执行make re
即可完全更新二进制文件。
- CMake-按正确顺序将项目与C运行时对象文件链接
- 无法将 GLFW 库与 Ubuntu 18.04 上的头文件链接
- 错误 VSP1011:无法获取调试信息.与 /配置文件链接器开关链接
- 将我的主输出库与测试可执行文件链接时出现问题
- CMake + Qt + GTest 文件链接
- 生成文件链接
- 使用LTO静态链接的可执行文件(链接时间优化):如何使用以前构建的库进行制作
- 生成文件链接错误
- 使用 c++ 生成文件的文件链接
- 生成文件:链接器错误
- 反转头文件/链接
- C++实现和头文件链接
- .cpp文件将不会与.h文件链接
- 将问题与多个文件链接在一起
- 编译三个C++文件.链接错误
- C++如何将我的主类与我的头文件链接起来
- 使文件链接问题 架构x86_64的未定义符号
- c++和mex文件链接错误
- 使用堆叠类生成文件链接问题
- 使用对象文件链接c++中的东西