GCC can automatically determine which compiler to use based on the file suffix. It uses the 'Objective-C' compiler for example on files with an '.m' suffix, or the FORTRAN compiler on files with a '.FOR' suffix.
But this is only when it is left up to GCC to choose which compiler to use.
Most vendor BSP's (board support packages) are advertised as C
Hence, it can be usefull to verify that some C sources can be compiled as C++. So let's see
how that can be done.
Save the simple test code below as "Hello.c".
#include <stdlib.h>
#include <stdio.h>
#ifdef __cplusplus
extern "C"
{
#endif
int main()
{
printf( "Hello world!" );
return EXIT_SUCCESS;
}
#ifdef __cplusplus
}
#endif
With the source file in the current directory, it can be compiled using:
gcc -S Hello.c
This will invoke gcc and lets it select the compiler based on the file's .c suffix. The -S option tells gcc to stop before the assembly stage of compilation and dump what it has generated from the compiler backend in the file Hello.s in the current directory.
Or:
gcc -x c -S Hello.c
Which will invoke gcc and tells it to ignore the .c suffix and use the C compiler regardless.
To test if the code in our "Hello.c" file is also syntactilly correct C++ code it can be compiled with the C++ compiler as follows:
gcc -x c++ -S Hello.c
The -x c++ option passed to gcc tells it to ignore the .c suffix and use the C++ compiler regardless.
It is easy to forget the correct option to select the compiler. That is why there are make files.
#Compile a source file either as C or as C++
Sources = Hello.c
#C++ compilation flags
CXXFLAGS += -Wall -Wextra -Wpedantic
CXXFLAGS += -std=c++11
#C compilation flags
CFLAGS += -Wall -Wextra -Wpedantic
CFLAGS += -std=c99
.PHONY: default
default:
@echo "supported targets are 'build-c' and 'build-cpp'"
build-c:
@echo "Compile " $(Sources) " as C"
$(CC) $(CFLAGS) -x c -S $(Sources)
build-cpp:
@echo "Compile " $(Sources) " as C++"
$(CXX) $(CXXFLAGS) -x c++ -S $(Sources)