Forcing GCC to compile .cpp file as C

27,018

Solution 1

The -x option for 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++)

Solution 2

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.

Share:
27,018
ralight
Author by

ralight

Hmm

Updated on July 09, 2022

Comments

  • ralight
    ralight almost 2 years

    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.

  • ralight
    ralight over 13 years
    How embarrassing, I must have paged right past it! Thanks very much, the same to everybody else who answered.
  • Mischo5500
    Mischo5500 over 8 years
    Works as charm and quickest mentioned solution possible I think.