【问题标题】:How to call static library function in a C++ class? [duplicate]如何在 C++ 类中调用静态库函数? [复制]
【发布时间】:2019-07-30 05:32:17
【问题描述】:

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

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

而class文件定义为:

#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 ld 中的 _main:找不到架构 x86_64 的符号 clang:错误:链接器命令失败,退出代码 1(使用 -v 查看调用)

【问题讨论】:

  • 将其定义为const char* CustomStatic::GetVersion()。请阅读一些 C++ 入门书籍。
  • @songyuanyao no static 这里需要
  • 你声明了函数mip::CustomStatic::GetVersion,但是定义了mip::GetVersion
  • 而且声明和定义也不匹配,所以这是通常的未定义引用重复。

标签: c++ static static-functions


【解决方案1】:

您的静态函数未在 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";
}

【讨论】:

    猜你喜欢
    • 2022-07-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多