2

I have a simple, representative C program, stored in a file called hello.c:

#include <stdio.h>
int main(void)
{
    printf('Hello, world\n');
    return 0;
}

On my Linux machine, I attempted to compile the program with gcc:

gcc hello.c

which returns an error:

undefined reference to "___gxx_personality_v0" ... etc

As has been discussed before in the context of C++, this problem arises in the linking stage, when gcc attempts to link C libraries to a C++ program, thus giving the error. In one of the answers, someone mentioned that the extension does matter, and that gcc requires the .c extension when compiling C files, and some other extension (e.g. .cpp) when compiling C++ files.

Question: How do I set gcc to use the file extension to determine which compiler to use, since gcc seems to be defaulting to C++ on my system? Specifying the language through the file extension alone doesn't seem to be enough. If I specify the language using the -x flag, gcc functions as expected.

gcc -x c hello.c
Community
  • 1
  • 1
Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105

1 Answers1

1

Typically, you let make decide this.

GNU Make has built in implicit rules, which automatically pick the right compiler.

Try a Makefile with these contents:

all: some_file.o some_other_file.o

And then place a some_file.cpp and some_other_file.c in the same directory, and gnu make will automatically pick the correct compiler. The linker, you may still have to provide yourself. When mixing C and C++, it's usually easiest to link with g++, like so:

program.exe: some_file.o some_other_file.o
    g++ -o $@ @^

This is the same as:

program.exe: some_file.o some_other_file.o
    g++ -o program.exe some_file.o some_other_file.o
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
Prof. Falken
  • 24,226
  • 19
  • 100
  • 173