Why does the function name in .o file different fr

2019-09-21 06:04发布

问题:

I compiled an .cc file with the following command, which is in Makefile code:

bin/bash ../libtool --silent --tag=CXX   --mode=compile g++ -DHAVE_CONFIG_H -I.
-I.. -I../include/ -I..    -g -O2 -MT rtpsession_inet.lo -MD -MP -MF 
.deps/rtpsession_inet.Tpo -c -o rtpsession_inet.lo rtpsession_inet.cc

There is a function named rtp_session_rtp_recv in the .cc file. However, it is said that the reference of this function cannot be found when I use the library generated by the Makefile.

So I checked the .o file generated by rtpsession_inet.cc and find that there is not a function named rtp_session_rtp_recv while the function name is changed to _Z20rtp_session_rtp_recvP11_RtpSessionj.

Meanwhile, there are several other functions changes their name, e.g. rtp_session_rtp_send -> _Z20rtp_session_rtp_sendP11_RtpSessionP4msgb.

But functions such as rtp_session_set_remote_addr_full are not changed at all.

What is the additional characters' meaning? How can I deal with this problem?

I compile the file in Linux and use command

nm rtpsession_inet.o

to read the .o file. (All the functions including the one with incorrect name are with T tag, which means the reference exists)

Thanks!

回答1:

This is called name mangling.

It's for the benefit of the linker. A C++ compiler is able to resolve multiple functions of the same name, based on their argument types. For example, you might have a function called print that takes an int argument, and another that takes a char* argument. The compiler knows which one to generate a call to based on what type of argument you pass to it.

Calls across translation units, though, have to be resolved by the linker, which typically is not aware of C++ overloading rules and has to resolve calls based only on the name. So the C++ compiler decorates the name with enough information to resolve the overload.

The C++ standard doesn't specify how this is done, but if you look at the name you can probably work out how the mangled name is generated.

How can I deal with this problem?

The compiler and linker should resolve calls correctly. What problem are you referring to?



回答2:

The additional characters are symbol "decorations" added by the compiler and are used to identify the function/method signature, i.e. the return type and the parameters. It helps the runtime determine which one of many functions of the same name (overloading) to invoke in any given invocation.