Why does the filename extension make a difference to compiling?

Viewed 291

I compile this code under CentOs8 with the GNU compiler:

#include <stdlib.h>

int main() {
    int *a = malloc(3 * sizeof(int));
    return 0;
}

When I name it a.cpp, both of the compile commands failed:

g++ -o a a.cpp
gcc -o a a.cpp

But after I rename it to a.c, this compile command succeeds:

gcc -o a a.c

This is C code, NOT C++ code. I believe using gcc or g++ should make the difference, but it seems the compiler only considers the filename extension.

Could you please provide some details on this?

1 Answers

C++ is going to error on your implicit cast from the void* returned by malloc() to int*. Whereas C allows implicit casts from void* to other pointer types.

Most compilers will default to looking at the file extension to determine language to compile to.

A man gcc reveals that all .c files default to being compiled as C. Whereas all .cc, .cp, .cxx, .cpp, .CPP, .c++, and .C (capital C) files are compiled as C++.

You can override this behavior force the language via the -x option for gcc/g++.

Example:

 gcc -x c++ foo.c -c   // compiles foo.c as C++ instead of C

gcc and g++ are typically the same binary on most unix systems. It just defaults to different behavior depending on its own argv[0] parameter.

There might be other behavior differences between explicitly using g++ and gcc versus the -x option. I'm not certain on that.

Related