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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4216247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:52:10  来源:igfitidea点击:

Forcing gcc to compile .cpp file as C

c++cgcccompilation

提问by ralight

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.

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

It uses #ifdef __cplusplusmacros 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++.

它使用#ifdef __cplusplus宏来保护 C++ 代码,这很棒。不幸的是,如果我尝试使用 gcc 进行编译,由于文件结尾,它会将其视为 C++。我知道 gcc 和 g++ 之间的区别 - 我不想编译为 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++.

有什么办法可以强制 gcc 将此文件视为 C 文件?我试过使用 eg --std=c99,但这正确地产生了 C99 对 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.

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

Thanks!

谢谢!

回答by Michael Mrozek

The -xoption to gcc lets you specify the language of all input files following it:

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

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

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

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

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

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

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

回答by Rob Kennedy

To compile foo.cppas a C file, you can create a new file named foo.cand put the following as its entire contents:

要将foo.cpp编译为 C 文件,您可以创建一个名为foo.c的新文件,并将以下内容作为其全部内容:

#include "foo.cpp"

Now compile foo.cinstead of foo.cpp.

现在编译foo.c而不是foo.cpp

We've used this to go the other way (compile a .cfile as C++) in order to start using C++ features in some files while preserving their decade-long CVS history. Also, we build using each platform's native compiler, not just GCC, so we didn't have to find the -xequivalent command for a half-dozen compilers, and then make our build system apply that command only to certain files.

我们已经用它来走另一条路(将.c文件编译为 C++),以便在某些文件中开始使用 C++ 功能,同时保留其长达十年的 CVS 历史。此外,我们使用每个平台的本机编译器进行构建,而不仅仅是 GCC,因此我们不必-x为六个编译器找到等效的命令,然后让我们的构建系统仅将该命令应用于某些文件。