linux - 如何在 src/中编译 .cpp 并在 build/中输出 .o

标签 linux makefile

在任何人将其标记为重复之前,让我先声明,我已经查看了这些问题但没有结果:

Makefiles: Get .cpp from one directory and put the compiled .o in another directory
Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?
Makefile, find sources in src directory tree and compile to .o in build file
C++ Makefile. .o in different subdirectories
Makefile: Compiling from directory to another directory

无论我尝试这些解决方案中的哪一个,我都无法正确构建此规则:

$(OBJ_DIR)/$(OBJ): $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
    $(CC) $(CPPFLAGS) -o $@ $<

这是完整的 makefile:

CPPFLAGS = -c -Wall -g \
        -I/usr/include/glib-2.0 \
        -I/usr/lib/x86_64-linux-gnu/glib-2.0/include \
        -I/user/include/gdk-pixbux-2.0 \
        -Iinclude
LFLAGS = -Wall -g
LIB = -lnotify
SRC_DIR = src
INCL_DIR = include
OBJ_DIR = build
TARGET_DIR = bin
SRC := $(subst $(SRC_DIR)/,,$(wildcard src/*.cpp))
INCL := $(subst $(INCL_DIR)/,,$(wildcard include/*.hpp))
OBJ := $(SRC:.cpp=.o)
TARGET = reminders
CC = g++

.PHONY: clean

$(TARGET_DIR)/$(TARGET): $(OBJ_DIR)/$(OBJ)
        $(CC) $(LFLAGS) -o $@ $^ $(LIB) 
        @echo Build successful

$(OBJ_DIR)/$(OBJ): $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
        $(CC) $(CPPFLAGS) -o $@ $< 

clean:
        rm -rf *.o build/* bin/* *~

在我的项目文件夹中,我有一个 src、bin 和 build 文件夹 在我的项目文件夹中有 main.cpp、reminder.hpp 和 controller.cpp。 这是我运行 make 时得到的结果:

Makefile:24: target 'main.o' doesn't match the target pattern
g++ -c -Wall -g -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/user/include/gdk-pixbux-2.0 -Iinclude -o mai
g++: fatal error: no input files
compilation terminated.
Makefile:25: recipe for target 'main.o' failed
make: *** [main.o] Error 1
shell returned 2

最佳答案

我建议你养成测试的习惯......好吧......一切

假设你的源目录包含

blue.cpp main.cpp red.cpp

现在在您的 makefile 中,试试这个:

$(info $(OBJ_DIR)/$(OBJ))

这会产生:

obj/blue.o main.o red.o

确认!现在你知道为什么你的规则失败了。您不能以这种方式添加前缀。模式是 $(OBJ_DIR)/%.o,但目标 main.o 与模式不匹配。

试试这个:

SRC := $(wildcard $(SRC_DIR)/*.cpp) # src/blue.cpp ...
OBJ := $(patsubst $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.o, $(SRC)) # obj/blue.o ...

$(TARGET_DIR)/$(TARGET): $(OBJ)
    $(CC) $(LFLAGS) -o $@ $^ $(LIB) 
    @echo Build successful

$(OBJ): $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
    $(CC) $(CPPFLAGS) -o $@ $< 

关于linux - 如何在 src/中编译 .cpp 并在 build/中输出 .o,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45643846/

相关文章:

linux - 在 TCSH/CSH 中设置 vi 风格的行编辑界面类似于 bash 中的 "set -o vi"

linux - 在 Linux 中使用 Mac OS 命令 'codesign'

C# .NET Core Console.ReadKey(true) 不会(总是)拦截 Ubuntu 上的 key

c - 如何在 Linux 上为 gcc 制作一个简单的 makefile?

linux - 从 Linux 用户空间检测修改过的文件

linux - 如何获得进程的准确共享内存大小?

c - makefile中的链接顺序是什么?

linux - 当我尝试安装 yuvmotionfps 时,无法识别的命令行选项 '-march'

iphone - 我为使用 makefile 构建的 iO 寻找库项目

c - 递归所有 C 文件