我的代码存储在main.cpp
文件包含void main()
函数和类MyClass
我现在想将其拆分为另一个文件。 IDE 是 Microsoft Visual Studio 2008 Professional。
myclass.h
#include <tchar.h>
class MyClass {
public:
static bool MyFunction (TCHAR* someStringArgument);
};
myclass.cpp
#include <tchar.h>
class MyClass {
private:
static bool someProperty;
static void doSomeOneTimeCode () {
if (!someProperty) {
/* do something */
someProperty = true;
}
}
public:
static bool MyFunction (TCHAR* someStringArgument) {
doSomeOneTimeCode();
/* do something */
return true;
}
};
bool MyClass::someProperty = false;
main.cpp
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "myclass.h"
void main () {
if (MyClass::MyFunction(TEXT("myString"))) {
_tprintf(TEXT("Yay\n"));
}
}
但是,当我尝试运行它时,出现两个链接器错误。
- LNK2019:无法解析的外部符号...(提到
MyClass::MyFunction
)
- LNK1120:1 个未解析的外部
我可以采取什么措施来防止这些链接器错误?
您在这里声明了两个类。其中之一是在myclass.h另一个是在myclass.cpp。请尝试以下方法:
myclass.h
#ifndef myclass_h_included
#define myclass_h_included
#include <tchar.h>
class MyClass {
private:
static bool someProperty;
static void doSomeOneTimeCode ();
public:
static bool MyFunction (TCHAR* someStringArgument);
};
#endif //!myclass_h_included
myclass.cpp
#include "myclass.h"
/*static*/ bool MyClass::someProperty = false;
void
MyClass::doSomeOneTimeCode() {
//...
}
bool
MyClass::MyFunction(TCHAR* someStringArgument) {
//...
}
Your main.cpp可以保持不变。我会关注本叔叔的 https://stackoverflow.com/questions/1549093/lnk2019-lnk1120-errors-when-splitting-my-code-in-multiple-files/1549128#1549128也回复一下。如果可能的话,应该隐藏一次初始化代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)