Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

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

Thanks!

question from:https://stackoverflow.com/questions/4216247/forcing-gcc-to-compile-cpp-file-as-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...