在任何人将其标记为重复之前,让我先声明,我已经查看了这些问题但没有结果:
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/