如果我没有头文件,如何使用静态库中的函数

Hat*_*ate 20 c c++ static-libraries

它是一种使用静态lib函数的方法,如果我没有头文件,只有*.a文件,但我知道函数签名?

Naw*_*waz 35

是的,如果您知道功能签名

只需在调用之前编写函数签名,如下所示:

void f(int); //it is as if you've included a header file

//then call it
f(100);
Run Code Online (Sandbox Code Playgroud)

您需要做的就是:链接slib.a到程序.

另外,请记住,如果静态库是用C编写的并且已经使用C编译器编译,那么extern "C"在编写函数签名时(如果使用C++编程)则需要使用,如下所示:

extern "C" void f(int); //it is as if you've included a header file

//then call it
f(100);
Run Code Online (Sandbox Code Playgroud)

或者,如果您有许多功能,那么您可以将它们组合在一起:

extern "C" 
{
   void f(int); 
   void g(int, int); 
   void h(int, const char*);
} 
Run Code Online (Sandbox Code Playgroud)

您可能更喜欢在命名空间中编写所有函数签名,以避免任何可能的名称冲突:

namespace capi
{
  extern "C" 
  {
    void f(int); 
    void g(int, int); 
    void h(int, const char*);
  } 
}

//use them as:

capi::f(100); 
capi::g(100,200); 
capi::h(100,200, "string"); 
Run Code Online (Sandbox Code Playgroud)

现在,您可以在头文件中编写所有这些内容,以便可以在文件中包含头文件.cpp(像往常一样),并调用函数(像往常一样).

希望有所帮助.

  • 换句话说:自己编写库的头文件. (13认同)

thi*_*ton 5

最简单的方法:在头文件中写入签名,包含它并链接到库.