C++ linking to libraries with makefile (newbe)
Asked Answered
F

2

7

I'm trying to understand how to use non standard libraries in my C++ projects. I have a few questions.

Lets say I want to use POCO library. So I downloaded it and build it using make (static build). Now I have bunch of .o files and .h files. There is a Path.h file and a Path.o file in different directories.

Now I want to use this module in my code. So i include the file using #include "Poco/Path.h". Do I have to modify makefile and add Path.o to my target ?

What happens when I use standard library ? Are those available only in header files ? I know that template code cannot be precompiled. What about the rest ?

Fitch answered 25/10, 2010 at 13:26 Comment(0)
C
9

Besides the .h and .o files, you will probably also have one or more libXXX.a and/or libXXX.so files. These are the actual library files that your application should link against.

To use the library, you include the relevant headers in your source file, and you change your makefile to tell the linker that it should also link your application to the XXX library. The typical linker-command for that is -lXXX and the linker will look for both libXXX.a and libXXX.so and use whichever seems most appropriate.

The standard library is not really different from external libraries, except that you don't have to specify it explicitly to the linker.

Coaler answered 25/10, 2010 at 13:59 Comment(1)
So .a file is a static library and .so is dynamic/shared ?Fitch
D
8

Your question seems to imply that you already have a makefile for your own code. If that's the case, then yes, you should modify the rule for your executable in that makefile. As Bart van Ingen Schenau points out, the POCO makefile probably assembled the objects files into libraries such as Poco/Libraries/libPoco.a, so you should use them instead of trying to pick out the object files you need. For instance, if right now your rule reads:

foo: foo.o bar.o
    g++ -lSomeLibrary $^ -o $@

you should change it to

foo: foo.o bar.o
    g++ -lSomeLibrary -LPoco/Libraries -lPoco $^ -o $@

(The second part of your question, "What happens... What about the rest?" is unclear to me.)

Note: It's a bad idea to #include "Poco/Path.h". This makes your code dependent on a directory structure, something it should not care about. It is much better to #include "Path.h" and tell the compiler where to find it: g++ -c -IPoco ....

Devalue answered 25/10, 2010 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.