C++ 具有不同字符集的项目内的链接错误

C++ Linking error within projects having different character set

本文关键字:项目 链接 错误 字符集 C++      更新时间:2023-10-16

我在VS 2005中编译C++项目解决方案时遇到链接错误。下面是场景。

我有一个解决方案,假设MySolution其中有 2 个项目命名

MyTestLib 是一个静态库类型的项目,具有字符集Use Multi-Byte Character Set且没有CLR支持

MyTestApp 是一款.exe应用程序,使用上述库和字符集Use Unicode Character SetCLR支持

MyTestLib中,有两个重载函数具有以下定义

int Class1::test1(int a)
{
    return a+4; 
}
bool Class1::test1(LPCTSTR param)
{
    return true;
}

MyTestApp从其代码中调用它们,例如

Class1 objcl1;
int a = objcl1.test1(12); //Works fine
Class1 objcl2;
string abc = "adsad";
bool t = objcl2.test1(abc.c_str()); //Error

调用test1(LPCTSTR)版本会出错

Error 1 error C2664: 'int TestLib::Class1::test1(int)' : cannot convert parameter 1 from 'const char *' to 'int'

如果我将语句更改为bool t = objcl2.test1((LPCTSTR)abc.c_str()); //Now linking Error然后我得到

Error 2 error LNK2001: unresolved external symbol "public: bool __thiscall TestLib::Class1::test1(wchar_t const *)" (?test1@Class1@TestLib@@$$FQAE_NPB_W@Z) TestProject.obj

但是如果我将项目MyTestApp字符集更改为Use Multi-Byte Character Set则所有错误都将得到解决。但是我无法更改项目字符集,因为还有其他依赖项。

有什么工作吗?

问题是,当您构建MyTestLib此签名时:

bool Class1::test1(LPCTSTR param);

成为

bool Class1::test1(const char * param);

因为LPCTSTR是一个宏,它根据构建发生时的"字符集"配置进行设置。

现在,当您使用为 UNICODE 配置的"字符集"构建MyTestApp时,它会将函数签名(我假设来自头文件)视为:

bool Class1::test1(wchar_t const * param);

因此,链接器没有希望将该函数链接到库中的实际内容。

解决方法是简单地不使用LPTCSTR作为函数的类型 - 实现的函数中该参数的类型将始终const char*,因此只需在函数声明中说明即可。