21

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?

Nawaz
  • 353,942
  • 115
  • 666
  • 851
Hate
  • 1,185
  • 3
  • 12
  • 24

2 Answers2

35

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.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 15
    In other words: Write the header file for the library yourself. – sth Oct 06 '11 at 10:25
  • How about calling classes and their member functions? I am facing similar situation but the functions I need are defined as members of a specific class defined in a .lib file. And I do know all the signatures. – DCoder Mar 04 '23 at 12:40
  • 1
    @DCoder: The members are non-static functions? If so, then it might have data members as well, with a layout which not known to your compilers. In short, your scenario is difficult, and you have to look for, or ask the developers of the lib to expose the class. – Nawaz Mar 04 '23 at 17:30
5

The easiest way: Write the signature in a header file, include it and link against the library.

thiton
  • 35,651
  • 4
  • 70
  • 100