我想了解一个类'ostream运算符“存在于对象文件中的位置。在下面的代码示例中,我设计了C ++类DeltaTimer,它是朋友的ostream运算符。下面是“nm DeltaTimer.o”的输出。 在此输出中对“ostream”进行Grepping会显示符号类型“U”,即未定义。但代码编译(main.cpp包含完整性)和链接成功,并按预期执行,这意味着没有任何未定义。但是我不明白ostream运算符在“nm”的输出中解析了什么,并且如果有人可以提供建议,我将不胜感激。 谢谢。
DeltaTimer.h:
template<>
struct traits<int> {
static double func()
{
return f();
}
};
template<>
struct traits<double> {
static double func()
{
return g();
}
};
DeltaTimer.cpp:
#ifndef DeltaTimer_h
#define DeltaTimer_h
#include <iostream>
class DeltaTimer
{
public:
DeltaTimer();
virtual ~DeltaTimer();
void Foo();
private:
int m_foo;
friend std::ostream& operator<<(std::ostream& os, const DeltaTimer& rDeltaTimer);
};
#endif // DeltaTimer_h
main.cpp中:
#include "DeltaTimer.h"
#include <iostream>
DeltaTimer::DeltaTimer() : m_foo(5)
{
std::cout << "DeltaTimer ctor" << std::endl;
}
DeltaTimer::~DeltaTimer()
{
std::cout << "DeltaTimer dtor" << std::endl;
}
void DeltaTimer::Foo()
{
std::cout << "DeltaTimer.m_foo == " << m_foo << std::endl;
}
std::ostream& operator<<(std::ostream& os, const DeltaTimer& rDeltaTimer)
{
os << "DeltaTimer[m_foo(" << rDeltaTimer.m_foo << ")]" << std::endl;
}
// This function is just a sanity-check for the output of "nm"
void Bar()
{
std::cout << "void Bar()" << std::endl;
}
输出“nm”:
#include "DeltaTimer.h"
#include <iostream>
int main()
{
DeltaTimer deltaTimer;
std::cout << deltaTimer << std::endl;
}
答案 0 :(得分:2)
这是因为nm
显示了错误的名字。要打印人类可读的,您需要使用--demangle
参数:
$ nm --demangle DeltaTimer.o
U __cxa_atexit
U __dso_handle
00000000000001a4 t _GLOBAL__sub_I__ZN10DeltaTimerC2Ev
U __gxx_personality_v0
0000000000000145 T Bar()
0000000000000167 t __static_initialization_and_destruction_0(int, int)
U operator delete(void*)
00000000000000f1 T operator<<(std::ostream&, DeltaTimer const&) // <== here's your guy!
00000000000000b0 T DeltaTimer::Foo()
0000000000000000 T DeltaTimer::DeltaTimer()
0000000000000000 T DeltaTimer::DeltaTimer()
000000000000008a T DeltaTimer::~DeltaTimer()
0000000000000040 T DeltaTimer::~DeltaTimer()
0000000000000040 T DeltaTimer::~DeltaTimer()
U std::ostream::operator<<(int)
U std::ostream::operator<<(std::ostream& (*)(std::ostream&))
U std::ios_base::Init::Init()
U std::ios_base::Init::~Init()
U std::cout
U std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)
0000000000000000 r std::piecewise_construct
0000000000000000 b std::__ioinit
U std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)
0000000000000000 V typeinfo for DeltaTimer
0000000000000000 V typeinfo name for DeltaTimer
0000000000000000 V vtable for DeltaTimer
U vtable for __cxxabiv1::__class_type_info
或者只是使用c++filt
。具体做法是:
$ echo _ZlsRSoRK10DeltaTimer | c++filt
operator<<(std::basic_ostream<char, std::char_traits<char> >&, DeltaTimer const&)