在实验《提高C++性能的编程技术》中第一个源代码是遇到了报错。。。。。
自己补全了点代码:
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Trace{
public:
Trace(const string &name);
~Trace();
void debug(const string &msg);
static bool traceIsActive;
static int t;
private:
string theFunctionName;
};
#include "Trace.h"
Trace::Trace(const string &name):theFunctionName(name)
{
if(traceIsActive)
{
cout<<"Enter function"<<name<<endl;
}
}
inline void Trace::debug(const string &msg)
{
if(traceIsActive)
{
cout<<msg<<endl;
}
}
Trace::~Trace()
{
if(traceIsActive)
{
cout<<"Exit function"<<theFunctionName<<endl;
}
}
#include <windows.h>
#include <iostream>
#include "Trace.h"
using namespace std;
int addOne( int x)
{
return x+1;
}
int main()
{
Trace::traceIsActive = false;
int j=1000000,y;
SYSTEMTIME t1,t2;
GetSystemTime(&t1);
for(int i=0 ; i< j ; i++)
{
y = addOne(i);
}
GetSystemTime(& t2);
cout<<t2.wSecond*1000+t2.wMilliseconds-t1.wSecond*1000-t1.wMilliseconds<<endl;
return 0;
}
上边的代码会报如下错误:mian.obj : error LNK2001: unresolved external symbol "public: static bool Trace::traceIsActive" (
?traceIsActive@Trace@@2_NA)Trace.obj : error LNK2001: unresolved external symbol "public: static bool Trace::traceIsActive" (
?traceIsActive@Trace@@2_NA)Debug/1_1.exe : fatal error LNK1120: 1 unresolved externals执行 link.exe 时出错.我在百度了好久找的答案是在Trace.cpp文件中加入 bool Trace::traceIsActive ;修改后源文件为:
#include "Trace。好“
bool Trace::traceIsActive ;//新增加的行
Trace::Trace(const string &name):theFunctionName(name)
{
if(traceIsActive)
{
cout<<"Enter function"<<name<<endl;
}
}
........
虽然可以编译通过了,不过我还想知道具体的原因,先谢过了
关于static变量的详细请看我的新帖http://blog.youkuaiyun.com/xt0916020331/article/details/7530195 说的不当之处请指出