C++:函数返回静态库中的字符串给出错误:在令牌之前':'预期的"="、""、";"、'asm'或'__attribute__'

C++ : Function return String in Static Library give Error : expected '=', ',', ';', 'asm' or '__attribute__' before ':' token

本文关键字:attribute asm 令牌 静态 返回 函数 字符串 C++ 错误 出错      更新时间:2023-10-16

嗨团队 我倾向于如何在C++中创建静态库,不幸的是,我下面的代码令人头疼,即使在谷歌谷歌几个小时之后,我也找不到问题所在。 遵循很多建议,但没有成功。

ercisstaticlib.h

#ifndef __ERCISSTATICLIB__
#define __ERCISSTATICLIB__
#include <string>
extern "C" std::string GetDatabaseName() ;
#endif  // ERCISSTATICLIB_H_INCLUDED

主.cpp

std::string GetDatabaseName()
{
    return "Testing";
}

错误信息

=== Build: Debug in ErcisLib (compiler: GNU GCC Compiler) ===
error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===

std::string是一个类。

extern c仅支持 C 类型,因为它会导致函数具有 C 签名。

C 签名意味着没有类,

因为 C 中没有类,只有 C++ 中的类。

您应该使用:

extern "C" const char* GetDatabaseName() ;

但需要注意不要返回指向局部变量的指针。

您还有其他选择:您可以放弃extern "C"并继续使用:

std::string GetDatabaseName();

如果您要将库与C++链接,则没有理由使用extern c。但是,如果您需要与C链接,则应选择第一个选项。