Alex Rivera | Logout

Difference in linkage between C and C++?

Asked 2010-01-08T08:08:38.087
10

I have read the existing questions on external/internal linkage over here on SO. My question is different - what happens if I have multiple definitions of the same variable with external linkage in different translation units under C and C++?

For example:

/*file1.c*/

typedef struct foo {
    int a;
    int b;
    int c;
} foo;

foo xyz;


/*file2.c*/

typedef struct abc {
    double x;
} foo;

foo xyz;

Using Dev-C++ and as a C program, the above program compiles and links perfectly; whereas it gives a multiple redefinition error if the same is compiled as a C++ program. Why should it work under C and what's the difference with C++? Is this behavior undefined and compiler-dependent? How "bad" is this code and what should I do if I want to refactor it (i've come across a lot of old code written like this)?

Edit
Report

1 Answer

0

You have found the One Definition Rule. Clearly your program has a bug, since

  • There can only be one object named foo once the program is linked.
  • If some source file includes all the header files, it will see two definitions of foo.

C++ compilers can get around #1 because of "name mangling": the name of your variable in the linked program may be different from the one you chose. In this case, it isn't required, but it's probably how your compiler detected the problem. #2, though, remains, so you can't do that.

If you really want to defeat the safety mechanism, you can disable mangling like this:

extern "C" struct abc foo;

… other file …

extern "C" struct foo foo;

extern "C" instructs the linker to use C ABI conventions.

answered 2010-01-08T08:30:25.407

Your Answer