How to use function from static library if I don't have header file

Hate picture Hate · Oct 6, 2011 · Viewed 13.4k times · Source

Is it a way to use function from static lib, if I don't have header file, only *.a file, but I know function signature?

Answer

Nawaz picture Nawaz · Oct 6, 2011

Yes, if you know the function signature

Just write the function signature before calling it, as:

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

//then call it
f(100);

All you need to do is : link the slib.a to the program.

Also, remember that, if the static library is written in C and has been compiled with C compiler, then you've to use extern "C" when writing the function signature (if you program in C++), as:

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

//then call it
f(100);

Alternatively, if you've many functions, then you can group them together as:

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

You may prefer writing all the function signatures in a namespace so as to avoid any possible name-collisions:

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"); 

Now you can write all these in a header file so that you could include the header file in your .cpp files (as usual), and call the function(s) (as usual).

Hope that helps.