Reputation: 1817
I'm surprised there is no official c++ library for postgres catching up with the standard. So I have to use the original c lipq. But how do I tell the linker to include it with CMake? I expect it to be a one short line in CMake.
All I see is find_package (what even a package is?, is's mentioned in the quick JetBrains' CMake tutorial, but not in the official), target_link_libraries, find_library.
All I'm asking for is like in Python (crossplatform) pip install my_library
and then import my_library
.
How do I do it?
Upvotes: 3
Views: 8760
Reputation: 2558
In CMake, a package is an external library (or tool) that can be located using scripts (either bundled with CMake, or written by someone else).
find_package
command runs that script. When a package is found, the script sets a number of variables pointing to include directories, libraries to link, etc.
A script for Postgres is included with CMake, so it should be possible to do something like this:
# This command attempts to find the library, REQUIRED argument is optional
find_package(PostgreSQL REQUIRED)
# Add include directories to your target. PRIVATE is useful with multi-target projects - see documentation of target_include_directories for more info
target_include_directories(MyTarget PRIVATE ${PostgreSQL_INCLUDE_DIRS})
# Add libraries to link your target againts. Again, PRIVATE is important for multi-target projects
target_link_libraries(MyTarget PRIVATE ${PostgreSQL_LIBRARIES})
That's a simple example of how find_package
can be used. Variables with PostgreSQL_
prefix are set by the script run by find_package
command and are described in here: FindPostgreSQL documentation
As a side note, find_library
can be used too, although it is "lower level". The command searches for a static/shared library, and is used to implement scripts used by find_package
. As long as a library you are trying to use has a find_package
script, it shouldn't be necessary to use find_library
.
UPDATE (CMake 3.14 and newer)
Starting with CMake 3.14, it is possible to use so called "imported target" for Postgres, which is a bit simpler and in line with modern CMake:
find_package(PostgreSQL REQUIRED)
# This line adds both include paths and libraries for Postgres
target_link_libraries(MyTarget PRIVATE PostgreSQL::PostgreSQL)
PostgreSQL::PostgreSQL
is imported target created by the Find
module. This target has include directories and libraries set as its INTERFACE
properties. This means that in the example above MyTarget
will "inherit" include directories and libraries from PostgreSQL::PostgreSQL
, without having to set them explicitly.
Upvotes: 12