【问题标题】:Link error in C++ by g++g++ 在 C++ 中的链接错误
【发布时间】:2010-02-04 14:34:46
【问题描述】:

请看下面的程序。为什么我会收到错误消息?

#include <stdlib.h>
#include <string>
#include <string.h>
#include <iostream>


using namespace std;

class serverData
{
public:
    static int serverTemp;
    static int server;
};
int main(int argc, char** argv)
{
    string s = "sajad bahmani";
    serverData::server = 90 ;

    const char * a = s.data();
    cout << a[0] << endl;

    return (EXIT_SUCCESS);
}

同时,我在尝试链接时收到此错误:

build/Debug/GNU-Linux-x86/main.o: In function `main':
/home/sb23/pr/main.cpp:14: undefined reference to `serverData::server'
collect2: ld returned 1 exit status

【问题讨论】:

  • 那是不是 编译错误,就是链接错误
  • 使用 s.c_str() 从 std::string 获取“C 风格”字符串,s.data() 不保证为空终止。

标签: c++ linker g++


【解决方案1】:

静态成员变量必须在您的 .CPP 文件之一中分配存储空间:

/* static */
int serverData::serverTemp;
int serverData::server;

【讨论】:

    【解决方案2】:

    您刚刚在类中声明了静态成员,但尚未定义它们。您需要在类之外定义它们。

    //definition
    int serverData::serverTemp; //implicitly initialized to 0
    int serverData::server = 5; // initialized to 5
    

    【讨论】:

    • 你确定第一个已经初始化了吗?
    • @Martin:是的,我很确定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多