如何在 C++ class 中调用静态库函数?
How to call static library function in a C++ class?
我有 class 其头文件定义为:
namespace mip {
class CustomStatic {
public:
static const char* GetVersion();
};
}
而class文件定义为:
#include "CustomStatic.h"
namespace mip {
static const char* GetVersion() {
return "hello";
}
}
我正在从我的主程序访问这个静态函数 class
#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
我得到的错误是:
Undefined symbols for architecture x86_64:
"mip::CustomStatic::GetVersion()", referenced from:
_main in MainApp-feb286.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code
1 (use -v to see invocation)
您的静态函数未在 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";
}
我有 class 其头文件定义为:
namespace mip {
class CustomStatic {
public:
static const char* GetVersion();
};
}
而class文件定义为:
#include "CustomStatic.h"
namespace mip {
static const char* GetVersion() {
return "hello";
}
}
我正在从我的主程序访问这个静态函数 class
#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
我得到的错误是:
Undefined symbols for architecture x86_64:
"mip::CustomStatic::GetVersion()", referenced from: _main in MainApp-feb286.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
您的静态函数未在 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";
}