47

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.

3
  • 1
    Sometimes when I see SO questions. I just want to scream a big RTFM!! man gcc. For this king of question it actually takes less time than writing the question. Commented Nov 18, 2010 at 15:21
  • 24
    I had the same problem because I wanted to compile pure C code within a .cpp file...obviously I'm quite a beginner concerning C. RTFM! is not such a good advice then. gcc man pages are 11.000 lines and it's kind of hard to find a solution in there if you don't know what to look for. Commented Nov 4, 2011 at 8:05
  • I disagree, reading documentation is never a loss of time, and the documentation of GCC is IMHO well written Commented Apr 26, 2021 at 14:26

2 Answers 2

78

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

Sign up to request clarification or add additional context in comments.

1 Comment

How embarrassing, I must have paged right past it! Thanks very much, the same to everybody else who answered.
18

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.

1 Comment

Works as charm and quickest mentioned solution possible I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.