使用 c++ 生成文件的文件链接

File linking with c++ makefile

本文关键字:文件 链接 c++ 使用      更新时间:2023-10-16

>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 而不是 CCCFLAGS ,因为您正在编译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即可完全更新二进制文件。