Home > database >  If I declare a function with extern "C", should I also define it that way?
If I declare a function with extern "C", should I also define it that way?

Time:10-15

In my header file, foo.h, I have:

#ifdef __cplusplus
extern "C" {
#endif

int foo(int x); 

#ifdef __cplusplus
}
#endif

Now, in foo.cpp, should I also use extern "C", and define:

#include "foo.h"

extern "C" { 
int foo(int x); 
};

? Or is the declaration enough to ensure C-linkage (no name mangling)?

CodePudding user response:

Marking the declaration by extern "C" is enough.

If the translation unit containing the declaration of your function has it with extern "C", the compiler will respect this when it finally encounters the implementation - and use a non-mangled symbol inside the object file.

See this on GodBolt.

Remember, though, that if your implementation does not see your header, nothing will make it extern "C" if you don't do so explicitly.

CodePudding user response:

It'd respect the first declaration

Except for functions with C linkage, a function declaration without a linkage specification shall not precede the first linkage specification for that function.

A function can be declared without a linkage specification after an explicit linkage specification has been seen; the linkage explicitly specified in the earlier declaration is not affected by such a function declaration.

§dcl.link

extern "C" int C1();
extern "C" int C1() { return 1; } // ok, C linkage, same as previous declaration

extern "C" int C2();
int C2() { return 1; } // ok, C linkage, preserve previous

int C3();
extern "C" int C3();   // error, only C   linkage can specified after first declaration


int F0();
int F0() { return 1; } // ok, C   linkage by default

extern "C  " int F1();
extern "C  " int F1() { return 1; } // ok, C   linkage

extern "C  " int F2();
int F2() { return 1; } // ok, C   linkage

int F3();
extern "C  " int F3(); // ok, C   linkage can specified after first declaration
  • Related