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!
The
-x
option to gcc lets you specify the language of all input files following it:If you only want to special-case that one file, you can use
-x none
to shut off the special treatment:(
your-filename.cpp
will be compiled as C, whileother-file-name.cpp
will use the extension and compile as C++)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:
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.