【问题标题】:static variable link error [duplicate]静态变量链接错误[重复]
【发布时间】:2012-03-06 03:26:53
【问题描述】:

我正在 Mac 上编写 C++ 代码。为什么编译的时候会出现这个错误?:

架构 i386 的未定义符号:“Log::theString”, 参考自: libTest.a(Log.o) 中的 Log::method(std::string) ld:未找到架构 i386 的符号 clang:错误:链接器命令失败 退出代码 1(使用 -v 查看调用)

不确定我的代码是否错误,或者我必须向 Xcode 添加其他标志。我当前的 XCode 配置是“静态库”项目的默认配置。

我的代码:

Log.h------------

#include <iostream>
#include <string>

using namespace std;

class Log{
public:
    static void method(string arg);
private:
    static string theString ;
};

Log.cpp ----

#include "Log.h"
#include <ostream>

void Log::method(string arg){
    theString = "hola";
    cout   << theString << endl; 
}

我从测试代码中调用“方法”,方式如下: 'Log::method("asd"):'

感谢您的帮助。

【问题讨论】:

    标签: c++ xcode static-libraries clang static-methods


    【解决方案1】:

    您必须在cpp 文件中定义静态。

    日志.cpp

    #include "Log.h"
    #include <ostream>
    
    string Log::theString;  // <---- define static here
    
    void Log::method(string arg){
        theString = "hola";
        cout   << theString << endl; 
    }
    

    您还应该从标题中删除using namespace std;。在你还可以的时候养成这个习惯。这将在包含标头的任何位置使用 std 污染全局命名空间。

    【讨论】:

    • 而不是初始化而不是定义,不(只是问)?
    • 也许更好的术语是它为字符串分配空间。
    • 非常感谢。你帮了我很多!
    • 标题中关于using namespace *; 的好点。如果你早点改掉这个习惯会更容易。
    • 只需将using namespace std; 放入您自己的命名空间声明中即可:P namespace your_custom_namespace { using namespace std; }
    【解决方案2】:

    您声明了static string theString;,但尚未定义它。

    包括

    string Log::theString;
    

    到您的cpp 文件

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多