Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

gcc

pragma

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.

like image 625
Joe Avatar asked Oct 20 '22 21:10

Joe


2 Answers

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

like image 199
Chris Dodd Avatar answered Oct 29 '22 01:10

Chris Dodd


No.

The documentation for the -x none option states:

Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes (as they are if -x has not been used at all).

So, there's no mention of further mechanisms, which makes me conclude that they don't exist.

Also note that your idea contains a logic problem: #pragma is a feature of some languages, so using it to specify which language is being used is very chicken-and-eggy.

like image 25
unwind Avatar answered Oct 28 '22 23:10

unwind