如何在C 类中调用静态库功能

How to call static library function in a C++ class?

本文关键字:调用 静态 功能      更新时间:2023-10-16

我有一个类,其标题文件定义为:

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()",从: _ main在mainapp-feb286.o ld中:符号(s)架构x86_64 clang:错误:链接命令失败,出口代码失败 1(使用-v查看调用)

您的静态功能在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";
}