Forcing gcc to compile .cpp file as C

2019-01-16 16:04发布

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.

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++.

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++.

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.

Thanks!

2条回答
男人必须洒脱
2楼-- · 2019-01-16 16:50

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

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

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 will be compiled as C, while other-file-name.cpp will use the extension and compile as C++)

查看更多
Melony?
3楼-- · 2019-01-16 16:53

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

#include "foo.cpp"

Now compile foo.c instead of foo.cpp.

We've used this to go the other way (compile a .c file 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 -x equivalent command for a half-dozen compilers, and then make our build system apply that command only to certain files.

查看更多
登录 后发表回答