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

2023-10-17C/C++开发问题
0

本文介绍了强制 GCC 将 .cpp 文件编译为 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++)

这篇关于强制 GCC 将 .cpp 文件编译为 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6