Getting Mangled C++ symbols from uncalled functions

65 views Asked by At

I would like to produce the symbols names of an included header, without calling any functions.

For example, if I have a header mylib.hpp:

namespace ns {

class MyClass{
    public:
    void printHello();
};
}

and in use_mylib.cpp I only include that header:

#include "mylib.hpp"

If I compile this using g++ -c use_mylib.cpp -o symbols.o, symbols.o will contain no symbols, as no functions are called. Is there a way to get the compiler to state I that it has a mangled ns::MyClass::printHello() _ZN2ns7MyClass10printHelloEv symbol, even if it's not called?

I was hoping for a switch in g++ to emit uncalled function symbols in symbols.o but that doesn't make any sense, since they're uncalled functions. Is there a user callable tool to get all the mangled names in a .cpp file, even when they're uncalled?

You may be asking why am I trying to do this. I'm trying to produce shared libray, and only have to compile the sources once. I want to ship the library with only "public" symbols defined, but I also want to test against symbols I'm not shipping. The approach of "everything public, then strip down the symbols." is something I'm looking at. Ideally I could just #include all the public headers to generate the needed mangled exports, and this is the long pole in the process right now.

2

There are 2 answers

0
Garrigan Stafford On

The symbol name would be in the translation unit (.cpp) file that has the definition of the function. The header only has declarations not definitions.

If you want to only have a subset of symbols publicly available you will need to pre-link the library when you build your public version, however when testing you should be able to test against a normally build static library and access the symbols since all non-static symbols will exist in the static library since the object files haven't been linked together.

1
273K On

If you don't want to call it, get the member function address:

namespace ns {

class MyClass {
 public:
  void printHello();
};

}  // namespace ns

auto p = &ns::MyClass::printHello;

https://godbolt.org/z/E463oM1o7:

p:
        .quad   _ZN2ns7MyClass10printHelloEv
        .quad   0