如何在C ++类中调用静态库函数?

时间:2019-03-08 07:54:02

标签: c++ static static-functions

我有一个其头文件定义为的类:

namespace mip {
    class CustomStatic {
        public:
            static const char* GetVersion();
    };
}

并且类文件定义为:

#include "CustomStatic.h"

namespace mip {
    static const char* GetVersion() {
        return "hello";
    }
}

我正在从主类访问此静态函数

#include "CustomStatic.h"

#include <iostream>

using std::cout;
using mip::CustomStatic;

int main() {
    const char *msg = mip::CustomStatic::GetVersion();
    cout << "Version " << msg << "\n";
}

当我尝试使用-

进行编译时
g++ -std=c++11 -I CustomStatic.h  MainApp.cpp CustomStatic.cpp

我收到以下错误消息:

  

x86_64体系结构的未定义符号:
  “ mip :: CustomStatic :: GetVersion()”,引用自:         MainApp-feb286.o中的_main ld:体系结构x86_64铛未找到符号:错误:链接器命令失败,并带有退出代码   1(使用-v查看调用)

1 个答案:

答案 0 :(得分:3)

您的静态功能未在cpp文件中正确实现...

您需要做类似的事情

//.h
namespace mip
{
    class CustomStatic
    {
         public:
            static const char* GetVersion();
    };
}


//.cpp -> note that no static keyword is required...
namespace mip
{
    const char* CustomStatic::GetVersion()
    {
        return "hello";
    }
}

//use
int main(int argc, char *argv[])
{
    const char* msg{mip::CustomStatic::GetVersion()};
    cout << "Version " << msg << "\n";
}