Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing GCC to compile .cpp file as 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.

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.

like image 213
ralight Avatar asked Nov 18 '10 15:11

ralight


People also ask

Can G ++ compile C file?

The compiler does not ensure that your program is logically correct. The compiler we use is the GNU (Gnu is not Unix) Open Source compiler. G++ is the name of the compiler. (Note: G++ also compiles C++ code, but since C is directly compatible with C++, so we can use it.).

Can you compile cpp with GCC?

cpp files but they will be treated as C++ files only. gcc can compile any . c or . cpp files but they will be treated as C and C++ respectively.

Does cpp compile to C?

No. C++ -> C was used only in the earliest phases of C++'s development and evolution. Most C++ compilers today compile directly to assembler or machine code. Borland C++ compiles directly to machine code, for example.

Why is GCC written in C++?

C++ is well-known and popular. It's nearly a superset of C90, which GCC was then written in. The C subset of C++ is as efficient as C. C++ "supports cleaner code in several significant cases." It never requires "uglier" code.


1 Answers

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

like image 134
Michael Mrozek Avatar answered Sep 24 '22 21:09

Michael Mrozek