我有一个最小但完整的 Makefile。如下:
OUT = example
INSTALL_DIR = /usr/local/bin
OBJECT = ./obj
SOURCE = ./src
SRC := $(shell find $(SOURCE) -name *.cc)
OBJ := $(SRC:%=$(OBJECT)/%.o)
DEPS := $(OBJ:.o=.d)
INC_DIRS := $(shell find $(SOURCE) -type d)
INC_FLAGS := $(addprefix -I,$(INC_DIRS))
CC = gcc
CFLAGS = -pipe -fmodules-ts -std=c++2a
DEBUG_FLAGS := $(CFLAGS) -g -Wall -Wextra
RELEASE_FLAGS := $(CFLAGS) -O3 -flto
debug: $(OBJ)
@echo "Building the DEBUG binary..."
@$(CC) $(OBJ) -o $(OUT) $(DEBUG_FLAGS)
@echo "The binary was built successfully!"
release: $(OBJ)
@echo "Building the RELEASE binary..."
@$(CC) $(OBJ) -o $(OUT) $(RELEASE_FLAGS)
@echo "The binary was built successfully!"
install: $(OUT)
@cp $(OUT) $(INSTALL_DIR)
uninstall:
@rm $(INSTALL_DIR)/$(OUT)
$(OBJECT)/%.cc.o: %.cc
@mkdir -p $(dir $@)
@echo "Building $@..."
@$(CC) $(CFLAGS) -c $< -o $@
.PHONY: clean
clean:
rm -rf $(OBJECT) $(OUT)
-include $(DEPS)
有一个名为“src”的目录,其中包含源文件。当我运行 make 时,我会收到一个编译错误,提示在使用模块之前必须先创建模块。如果我手动创建它们,那么我将能够使用“Make”,它会起作用,然后它就会起作用。有没有办法自动创建它们?
我建议使用
g++-11
而不仅仅是gcc
,因为版本<=10 do not really include module support asides from the deprecated TS. Then also, use flag -std=c++20
。
此外,我有使用 gcc 依赖文件的(痛苦的)经验,因为该特定功能并未真正完全实现。最后我检查了(21 年 11 月开始)依赖文件实际上并没有执行与模块相关的任何操作。
话虽这么说,你写的东西应该有效。如果模块的编译器支持完成的话,它就会完成。
可能您在编译依赖项时颠倒了顺序。
在 C++20 模块中,编译顺序很重要。 这是该技术的特点。它也发生在其他具有模块系统的语言中,例如 Fortran 等。
Hello World
与 C++20 模块这里是有关如何创建 Makefile 以在 GCC 11.2 上使用 C++20 模块的经过测试的演示。
如果您愿意,可以在此存储库中克隆以下代码。
Project
|- func.cpp
|- main.cpp
|- Makefile
.PHONY: all clean run
COMPILER = g++
COMPILER_FLAG = -std=c++20 -fmodules-ts
default: all
run: all
./App.exe
all: App.exe
# VERY IMPORTAN! In compilling modules the order of compilation matters.
# This is a characteristic of the technology. Check for example to swap
# the two lines bellow:
# App.exe: main.o func.o
App.exe: func.o main.o
${COMPILER} $^ -o App
%.o: %.cpp
${COMPILER} -c ${COMPILER_FLAG} $<
clean:
@-rm App
@-rm func.o
@-rm main.o
@-rm -r gcm.cache
module;
export module MyModule;
export int func(int a, int b) { // definition
return a + b;
}
#include <iostream>
import MyModule;
int main() {
std::cout << "hello world! -----> " << func(1,2);
}
# powershell
> git clone https://github.com/fvilante/cpp20_modules_with_gcc_demo.git
> cd Cpp20_modules_test
❯ make run
./App.exe
hello world! -----> 3
> make clean
感谢您的阅读!