Search code examples
c++cgccpragma

Does gcc have a pragma to define file type/compiler?


GCC automatically switches between compilers based on file extension (.c, .cc), by command line parameter (-x) or by calling the appropriate compiler directly (g++ as opposed to gcc, say).

Is there any way to override these using a pragma inside of a file?

Updated, after comment:

I'm converting a code base that is currently 50/50 C & C++ to be entirely compiled with the C++ compiler. This is to allow the current "C" modules to call onto a new C++ base that I cannot change (and don't wish to wrap). I would like to keep the extension as .c for the files that really are C, even though they now have C++ linkage. I think leaving them as ".c" indicates why they are as they are (I'm thinking of future generations here! ;-) ) but it's also a large job to change the build system to accommodate each changed C file name. Even worse, a tiny subset of C files won't convert to C++ sanely, so providing they don't call onto the C++ base I want to leave them as C. Rewriting them isn't an option though, the risks to the stability of the project are too great.


Solution

  • You mentioned having a build system issue that prompted this question. I once solved a similar problem by using comments in the source file. I used a Makefile rule like:

    %.o: %.c
            $(CC) $(CFLAGS) `if head -1 $< | grep -q 'C++'; then echo '-x c++'; else echo '-x c'; fi` -c -o $@ $<
    

    Now if a source file began with a comment line like /* C++ */ it would be compiled as C++ and otherwise it would be compiled as C (regardless of whether CC=gcc or CC=g++)