【问题标题】:How to generate .o files in different directory using Makefile [duplicate]如何使用Makefile在不同目录中生成.o文件[重复]
【发布时间】:2021-10-24 13:23:34
【问题描述】:

我正在使用 Makefile 来编译我的源文件并将其与 sfml 库链接。 这完美地工作。唯一的问题:它在与源文件 (.cpp) 相同的目录中生成 .o 文件(和 .exe)。我希望我的 Makefile 将它们生成为不同的文件(例如 /obj)。我怎么能这样做?

这是 Makefile :

CXX      = g++
INCL_DIR = src/include
LIB_DIR  = src/lib
SRC      = $(wildcard *.cpp)
OBJ      = $(SRC:.cpp=.o)

all: compile link

compile:
    $(CXX) -I $(INCL_DIR) -c $(SRC)

link:
    $(CXX) $(OBJ) -o main -L$(LIB_DIR) -lsfml-graphics -lsfml-window -lsfml-system

【问题讨论】:

标签: c++ makefile


【解决方案1】:

这是我的一个 Makefile 的剪切和粘贴:

# This defines subdirectories. I have sources in ./src.
SRCDIR := src
OBJDIR := obj
BINDIR := bin

# Just a bunch of -I commands to the compiler.
# You probably don't need these.    
INCLUDES += -I. -I./generated -I/usr/local/include -I/usr/local/include/antlr4-runtime

# This gives options to g++. -O3 is optimization.
# The includes are from above, but you probably could ignore.
# --std=c++17 means this is C++ 17 rather than something older.
CXXFLAGS = -O3 ${INCLUDES} --std=c++17 -g ${AUTO_ARGUMENT}

# You can probably skip this.
LDFLAGS += -L/usr/local/lib

# This defines the command for building. You can probably make
# this much shorter.    
COMPILE.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c

# This is a link command. You'll see I'm forcing a static link
# against a library, but of course, yo udon't need that.
${BINDIR}/wave: ${OBJECTS}
    ${CXX} ${OBJECTS} ${LDFLAGS} /usr/local/lib/libantlr4-runtime.a -o ${BINDIR}/wave

# Because sources can be in two different directories, I have
# two generic rules. This rule builds the generated source
# (output from antlr4) into obj/foo.o    
${OBJDIR}/%.o : generated/%.cpp
    $(COMPILE.cc) $(OUTPUT_OPTION) $<

# Same thing but the code i'm actually writing.
# Make already knows about $(OUTPUT_OPTION) and $< is
# the input.
${OBJDIR}/%.o : src/%.cpp
    $(COMPILE.cc) $(OUTPUT_OPTION) $<

我在 ./src 中有我的源代码,在 ./generated 中有一些生成的文件(来自 antlr4),所以我有两条规则来构建它们。

因此,您制定了一条规则(或在我的情况下,两条规则)在 ${OBJDIR} 目录中生成 .o 文件,然后在 ${BINDIR} 中生成二进制文件。

【讨论】:

  • 你好约瑟夫。对不起,我正在努力理解您的 makefile。有一些使用但未定义的变量,如 TARGET_ARCH 是否正常?它仍然有效吗?
  • 我做了一些清理工作,但不是全部。由于 TARGET_ARCH 是未定义的,它变成 null 并且不应该伤害任何东西。或者你可以编辑它。让我编辑我的答案,然后我会结束内联 cmets。
猜你喜欢
  • 1970-01-01
  • 2015-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
相关资源
最近更新 更多