【发布时间】:2017-08-25 17:09:48
【问题描述】:
我在为位于 2 个不同目录中的 cpp 文件创建对象时遇到问题,如下所示:
- Project-xyz
- Hello
- Hello.cpp
- World
- Main.cpp
- World.cpp
- Makefile
为了更清楚,这里是代码的外观(只是一个虚拟代码)。
你好/Hello.h
#ifndef HELLO_H
#define HELLO_H
void HelloPrint();
#endif // HELLO_H
你好/Hell.cpp
#include <iostream>
#include "Hello.h"
void HelloPrint()
{
std::cout <<"Hello" << std::endl;
}
world/World.h
#ifndef WORLD_H
#define WORLD_H
void WorldPrint();
#endif // WORLD_H
world/World.cpp
#include <iostream>
#include "World.h"
void WorldPrint()
{
std::cout <<"World!" << std::endl;
}
世界/Makefile 使用here 中给出的生成文件。哪个工作正常。但它不会创建任何 obj 文件。
# set non-optional compiler flags here
CXXFLAGS += -std=c++11 -Wall -Wextra -pedantic-errors
# set non-optional preprocessor flags here
# eg. project specific include directories
CPPFLAGS +=
# find cpp files in subdirectories
SOURCES := $(shell find . -name '*.cpp')
SOURCES += $(shell find ../hello -name '*.cpp')
# find headers
HEADERS := $(shell find . -name '*.h')
OUTPUT := HelloWorld
# Everything depends on the output
all: $(OUTPUT)
# The output depends on sources and headers
$(OUTPUT): $(SOURCES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $(OUTPUT) $(SOURCES)
clean:
$(RM) $(OUTPUT)
我正在寻找一个使用 makefile 的解决方案,它在特定目录中生成 obj 文件,如 here 所示。
现在我正在尝试使用下面的 make 文件为 world/objdir/hello.o 中的 hello/hello.cpp 文件生成 obj 文件。这是行不通的。 如何让它工作?
世界/Makefile
GCC=g++
CPPFLAGS=-c -Wall
LDFLAGS=
OBJDIR=objdir
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
TARGET=HelloWorld
.PHONY: all clean
all: $(OBJDIR) $(TARGET)
$(OBJDIR):
mkdir $(OBJDIR)
$(OBJDIR)/%.o: %.cpp
$(GCC) $(CPPFLAGS) -c $< -o $@
$(TARGET): $(OBJ)
$(GCC) $(LDFLAGS) -o $@ $^
clean:
@rm -f $(TARGET) $(wildcard *.o)
@rm -rf $(OBJDIR)
当我尝试运行 make 时,它会抛出以下错误。
g++ -c -Wall -c main.cpp ../hello/Hello.cpp -o objdir/main.o
g++: fatal error: cannot specify -o with -c, -S or -E with multiple files
compilation terminated.
make: *** [objdir/main.o] Error 4
它无法为 hello/Hello.cpp 文件生成 obj 文件,因此抛出此错误。
感谢 makefile Masters 的任何帮助! :)
【问题讨论】:
-
-o 必须在链接“阶段”中使用:
link: $(GCC) -o $(TARGET) $(OBJ)。顺便说一句,您的项目中没有 main -
对不起,我错过了添加。这只是一个简单的代码,我试图解释这个问题。在这里 #include "../hello/Hello.h" #include "World.h" int main() { HelloPrint();世界打印(); }