How to use functions from static libraries

351 Views Asked by At

I am trying to figure out how to use static libraries (with the .a extension) as "effective" as possible. The reason I looked into static libraries is because I want to put code from several .h and .cpp files into a single file, which I then easily can move around for different projects.

I created a file geometry.h containing e.g.

double hypotenuse(double, double);

and a geometry.cpp file with the definition. I created a libgeo.a file and tested it in another program (main.cpp, say). I compiled this program like this:

g++ main.cpp -o test -L. -lgeo

I get the error 'hypotenuse' was not declared in this scope. The obvious remedy to this is to add the declaration double hypotenuse(double, double); in main.cpp, just as in geometry.h, but why would I want to do that for ever class and function contained in the library? I could write #include "geometry.h" in main.cpp, but then I must always have the header files and the reason why I wanted to use libraries was to have a single file with useful code.

I thought that the reason to have a library was so that you wouldn't need to bring a bunch of different files everywhere you go, but what is the point in .a files if I have to re-declare everything I need? Is there something I've missed? How are .a libraries usually used?

1

There are 1 best solutions below

0
On

That's what header files are for :)

It sounds like you need a "geometry.h" ... and it will certainly have more than one class in it once your program evolves.

PS:

Please lose the annoying "anonymous arguments":

double hypotenuse(double, double); // BAD

double hypotenuse(double a, double b); // BETTER