Adrien
Adrien

Reputation: 449

How to force g++ to create C symbol name

I have a function called init in a cpp file, but when I compile it, g++ creates in the object file a symbol named _Z4initv, so when I link after with ld with the option -e init, obviously ld doesn't recognize the symbol init. Is there a way to create symbols name in C style with g++ ?

Upvotes: 0

Views: 578

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

If you have a definition like e.g.

void init() { ... /* some code */ ... }

Then to inhibit name mangling you need to declare it as extern "C":

extern "C" void init() { ... /* some code */ ... }

If you have a declaration in a header file that you want to include in a C source file you need to check if you're including the header file in a C or C++ source file, using the __cplusplus macro:

#ifdef __cplusplus
extern "C"
#endif
void init(void);

Note that the function in the header file has to be declared with void in the argument list, if it doesn't take any arguments. That's because the declaration void init() means something else in C.

Upvotes: 0

Related Questions