我可以指示 g++ 编译扩展名与“.cpp”等不同的 C++ 源文件吗?

Can I instruct g++ to compile a c++ source file with a different extension than ".cpp" etc?

我正在编写一个 library/framework,它可以配置为仅 CPU 实现或混合 CPU-GPU 实现。例如,假设我有以下文件:

LibraryMainCode.cpp
LibraryMainCode.h
Numerics.cpp
Numerics.h

对于仅 CPU 的实现,构建很简单:

g++ -I. -c Numerics.cpp -o Numerics.o
g++ -I. -c LibraryMainCode.cpp -o LibraryMainCode.o
(linking, etc)

对于混合实现,构建稍微复杂一点:

g++ -I. -c Numerics.cpp -o Numerics.o
g++ -I. -c LibraryMainCode.cpp -o LibraryMainCode.o
nvcc -I. -x cu -dc LibraryMainCode.cpp -o XLibraryMainCode.o
(linking, etc)

即,我将这些“混合”文件中的每一个编译两次,一次作为 cpu-only 对象,一次也使用 gpu 代码。

但是,我的代码库增长得非常快,我只想让文件扩展名决定文件的编译方式。例如,我可以更改文件名:

LibraryMainCode.cpp
LibraryMainCode.h
Numerics.cppx
Numerics.h

然后,我的 makefile 可以简单地找到这些“.cppx”文件并相应地编译它们。不幸的是,如果我编写一个扩展名为“.cppx”的简单“Hello World”程序,那么 g++ 将无法编译它。

我知道 g++ 有 a list of recognized c++ extensions 所以我可以为这些混合文件使用诸如“.cxx”之类的东西,否则为“.cpp”,但我想强调混合文件 不一定是标准的 C++ 代码,必须在 makefile 中进行特殊处理。

有没有简单的方法强制让g++编译任意扩展名的源文件?

您可以在包含编译器选项的 makefile 中使用字符串变量,并将其用于每个 cpp 文件。

您可以使用 -x <lang> 选项明确指定源文件的语言:

g++ -x c++ file.strange_extension