强制 GCC 将 .cpp 文件编译为 C

2022-01-04 00:00:00 gcc compilation c c++

我有一个外部提供的 .cpp 文件.它是 C 兼容代码和一些 C++ 的混合体.C++ 代码只是对 C 的封装,以利用 C++ 的特性.

I have an externally provided .cpp file. It is a mixture of C compatible code and a bit of C++ as well. The C++ code is just a wrapper around the C to take advantage of C++ features.

它使用 #ifdef __cplusplus 宏来保护 C++ 代码,这很棒.不幸的是,如果我尝试使用 GCC 进行编译,由于文件结尾,它会将其视为 C++.我知道 gccg++ 之间的区别 - 我不想编译为 C++.

It uses #ifdef __cplusplus macros to protect the C++ code, which is great. Unfortunately, if I try to compile using GCC, it treats it as C++ because of the file ending. I'm aware of the differences between gcc and g++ - I don't want to compile as C++.

有什么办法可以强制 GCC 将此文件视为 C 文件?我试过使用例如--std=c99,但这会正确地产生 C99 对 C++ 无效的错误.

Is there any way I can force GCC to treat this file as a C file? I've tried using e.g. --std=c99, but this correctly produces the error that C99 isn't valid for C++.

将文件重命名为 .c 是可行的,但如果可能的话,我想避免这种情况,因为它是外部提供的,最好将其保留为原始副本.

Renaming the file to .c works, but I'd like to avoid this if possible because it's externally provided and it'd be nice for it to remain as a pristine copy.

推荐答案

gcc-x 选项允许您指定其后的所有输入文件的语言:

The -x option for gcc lets you specify the language of all input files following it:

$ gcc -x c your-file-name.cpp

如果你只想对那个文件进行特殊处理,你可以使用 -x none 来关闭特殊处理:

If you only want to special-case that one file, you can use -x none to shut off the special treatment:

$ gcc -x c your-filename.cpp -x none other-file-name.cpp

(your-filename.cpp 将编译为 C,而 other-file-name.cpp 将使用扩展名并编译为 C++)

(your-filename.cpp will be compiled as C, while other-file-name.cpp will use the extension and compile as C++)

相关文章