1

Problem Background:

I'm reading the code written by someone else but could not understand extern "C".
Hence, I did a small experiment to move one of the headers file out of the extern "C" block.

// C++ source file

#include pkg_hander.h // Experiment: moving pkg_handler.h out of the extern "C" block

extern "C"
{
/*
 * Other related C headers, we need to use some functions declared in them
 */
#include check_stock.h
#include check_customer_detail.h
...
...
}

The linker complains that undefined reference to to symbolNames:

<path>/pkg_handler.h:69: undefined reference to `print_traces()'
<path>/pkg_handler:69: undefined reference to `order_timeout()'
collect2: error: ld returned 1 exit status

Functions print_traces() and order_timeout() are declared from pkg_hander.h. The symbols of both functions can be found in nm libpkghandler.so:

000000000021454a T print_traces
00000000002be1a8 T order_timeout

Questions:

I didn't change the C library object file and both symbols still exist in the C library.

Why g++ gives this error? Is the linker unable to link print_traces() function to print_traces?

Community
  • 1
  • 1
ZR_xdhp
  • 361
  • 2
  • 13
  • https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c – DeducibleSteak Feb 28 '20 at 11:30
  • 1
    Does this answer your question? [What is the effect of extern "C" in C++?](https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c) – DeducibleSteak Feb 28 '20 at 11:31
  • it partially answered my question. However, there is no function overloading in my case and both `print_traces()` and `order_timeout()` are not taking any parameters. – ZR_xdhp Feb 28 '20 at 11:34
  • I understand that name mangling happens when there are overloading functions taking different parameters. But this does not appear to be the case in my code: function names are matching the symbol names && both does not have parameters... but the linker still failed to link them when I moved header file out of the `extern "C"` block – ZR_xdhp Feb 28 '20 at 11:36
  • 2
    It is totally irrelevant whether or not you do overloading in your particular source/header files, you could always have other headers/source that is compiled completely separately, where you have many overloads of a function with the same name, none of which ever appear in the same compilation translation unit, but need to end up linked together and working properly, so the compiler always needs to, and does, perform name mangling, for any C++ functions. – DeducibleSteak Feb 28 '20 at 11:43
  • Thanks very much! Your answer certainly corrected one of my misunderstanding of the name mangling concept! – ZR_xdhp Feb 28 '20 at 11:45
  • 1
    Also here is a useful tool to play around with: https://godbolt.org/z/CRTZsW – DeducibleSteak Feb 28 '20 at 11:50

0 Answers0