SlideShare a Scribd company logo
Richard Thomson
Senior Software Engineer, NVIDIA
@LegalizeAdulthd
http://LegalizeAdulthood.wordpress.com
legalize@xmission.com
Outline
 Review of C++ Libraries
 find_package
 pkg-config
 Custom Find Module
C++ Library Review
 Source files include library headers
 Executable linked against libraries
Library Header Complications
 May include headers from other libraries
 May require specific preprocessor
definitions
 May have different names on different
platforms
 May have different names based on build
configuration
Library Link Complications
 May depend on other libraries
 May require specific runtime constraints, e.g.
Windows C/C++ runtime library variants
 May have different names on different platforms
 May have different names based on build
configuration
 Library location may depend on build configuration
CMake Requirements
 Build Requirements
 What is needed to build this target?
 Usage Requirements
 What is needed to use a target?
 Requirement examples:
○ Compilation flags
○ Preprocessor definitions
○ Include directories
○ Link directories
○ Link dependencies
 Requirements are propagated transitively by
CMake between targets
CMake Target Requirements
 PRIVATE
 Build requirements for the target
 Imposes no usage requirement
 INTERFACE
 Usage requirements for the target
 Imposes no build requirements
 PUBLIC
 Combination of PRIVATE and INTERFACE
 Imposes build and usage requirements
CMake Properties
 A property is a name/value pair
 CMake properties:
 Global properties
 Project properties
 Directory properties
 Target properties
 Source file properties
 Build requirements are properties
 Usage requirements are properties
CMake Modules
 A module is just a text file containing CMake
commands
 Typically a module defines functions and macros
 Usually named XXX.cmake
 include(XXX) loads the module XXX.cmake
 CMake has a module search path used to locate
module files
Imported Targets
 Imported targets supply usage
requirements
 A find module may create imported targets
for the found library
 Usage requirements are associated with the
imported target via target properties
 Prefer imported targets for found libraries
Library Flavors
 Header Only Library
 Static Library
 Dynamic Library
 Plug-In Library
Header Only Library
 Implementation exists only as headers
 Library dependencies are linked into the
executable
 Executable and library must use compatible
compilation flags
 Unused code may be detected by the linker
Header Only Library by Hand
cmake_minimum_required(VERSION 3.16)
project(hello VERSION 1.0 LANGUAGES CXX)
add_executable(hello hello.cpp)
target_compile_options(hello PRIVATE –Wall)
target_compile_definitions(hello PRIVATE HAVE_IOSTREAMS)
target_include_directories(hello PRIVATE greet/include)
Static Library
 Binds object code into the executable
 Library dependencies are linked into the
executable
 Executable and library must use compatible
compilation flags
 Unused code may be detected by the linker
Static Library by Hand
cmake_minimum_required(VERSION 3.16)
project(hello VERSION 1.0 LANGUAGES CXX)
add_executable(hello hello.cpp)
target_compile_options(hello PRIVATE –Wall)
target_compile_definitions(hello PRIVATE HAVE_IOSTREAMS)
target_include_directories(hello PRIVATE greet/include)
target_link_libraries(hello PRIVATE greet/lib/libgreet.a)
Dynamic Library
 Binds references into the executable
 Must be deployed with the executable
 Library may be versioned
 Executable and library must use compatible
compilation flags
Dynamic Library by Hand
cmake_minimum_required(VERSION 3.16)
project(hello VERSION 1.0 LANGUAGES CXX)
add_executable(hello hello.cpp)
target_compile_options(hello PRIVATE –Wall)
target_compile_definitions(hello PRIVATE HAVE_IOSTREAMS)
target_include_directories(hello PRIVATE greet/include)
target_link_libraries(hello
PRIVATE greet/lib/libgreet.so)
Plug-In Library
 Dynamic library that is accessed at runtime
 Executable does not directly bind to the
library
 Executable queries plug-in for function entry
points
 Executable and library must use compatible
compilation flags
Plug-In Library by Hand
cmake_minimum_required(VERSION 3.16)
project(hello VERSION 1.0 LANGUAGES CXX)
add_executable(hello hello.cpp)
target_compile_options(hello PRIVATE –Wall)
target_compile_definitions(hello PRIVATE HAVE_IOSTREAMS)
target_include_directories(hello PRIVATE greet/include)
Library by Hand Shortcomings
 Consuming executable littered with library
implementation details
 Compilation options are compiler specific
 Location of headers is assumed
 Location of library is assumed
 Doesn’t select debug or release library
 Name of library is assumed
find_package
find_package(<PackageName> [version]
[EXACT] [QUIET] [MODULE] [REQUIRED]
[[COMPONENTS] [components...]]
[OPTIONAL_COMPONENTS components...]
[NO_POLICY_SCOPE])
 Finds and loads settings from an external
project
 Sets <PackageName>_FOUND if found
 Sucess results in variables and imported
targets describing the found package
 Unifies header only, static and dynamic
libraries
Find Modules
 find_package looks for a Find Module for
the requested package
 The CMake module search path is used to
located the Find Module
 A Find Module is named FindXXX.cmake
 CMake ships with many find modules
find_package Example
cmake_minimum_required(VERSION 3.16)
project(hello VERSION 1.0 LANGUAGES CXX)
add_executable(hello hello.cpp)
find_package(Greeting 1.0 REQUIRED)
target_link_libraries(hello PRIVATE Greeting::greet)
pkg-config
 pkg-config originated in Unix, but is
available for Unix, macOS and Windows
 pkg-config describes usage requirements
for installed libraries
 CMake’s FindPkgConfig module can create
imported targets for pkg-config libraries
pkg-config Example
cmake_minimum_required(VERSION 3.16)
project(hello VERSION 1.0 LANGUAGES CXX)
find_package(PkgConfig REQUIRED)
add_executable(hello hello.cpp)
pkg_check_modules(Greeting REQUIRED IMPORTED_TARGET
greet=1.0)
target_link_libraries(hello PRIVATE PkgConfig::Greeting)
Custom Find Module
 Write your own find module when CMake
has no find module for the library
 Determines usage requirements:
 Compile options
 Compile definitions
 Include directories
 Link options
 Link directories
 Library filename
 Create imported target(s) for the library
Find Module Outline
1. Input data is described by find_package
2. Locate header files
3. Locate library files
4. Locate dependencies
5. Call find_package_handle_standard_args
to communicate results to find_package
6. If everything found:
1. Create imported target
2. Set target properties
Finding Things
 find_file
 find_program
 find_path
 find_library
 find_package
find_file
find_file(<var>
name | NAMES name1 [name2...]
[HINTS path1 [path2...ENV var]]
[PATHS path1 [path2...ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[NO_DEFAULT_PATH])
 Locates a file according to name, location, suffix
 Stores the result in <var>
 Consult documentation for more options and
details on search behavior
find_program
find_program(<var>
name | NAMES name1 [name2...]
[HINTS path1 [path2...ENV var]]
[PATHS path1 [path2...ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[NO_DEFAULT_PATH])
 Similar to find_file
 Locates an executable program
 Handles platform specific conventions, e.g.
foo.exe on Windows
find_path
find_path(<var>
name | NAMES name1 [name2...]
[HINTS path1 [path2...ENV var]]
[PATHS path1 [path2...ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[NO_DEFAULT_PATH])
 Similar to find_file
 Locates a directory containing a file
find_library
find_library(<var>
name | NAMES name1 [name2...]
[HINTS path1 [path2...ENV var]]
[PATHS path1 [path2...ENV var]]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[DOC "cache documentation string"]
[NO_DEFAULT_PATH])
 Similar to find_file
 Handles platform specific library forms, e.g.
libfoo.a, foo.dll, foo.lib
 Use find_package to locate your
dependencies
find_package
find_package_handle_standard_ar
gs
find_package_handle_standard_args(<PackageName>
[FOUND_VAR <result-var>]
[REQUIRED_VARS <required-var>...]
[VERSION_VAR <version-var>]
[HANDLE_COMPONENTS]
[CONFIG_MODE]
[REASON_FAILURE_MESSAGE <message>]
[FAIL_MESSAGE <message>]
)
 find_package(PackageHandleStandardArgs)
 Use REQUIRED_VARS to list requirements:
found files, directories, libraries, etc.
 Combined result is in <result-var>
Creating Imported Targets
add_library(<name>
<SHARED|STATIC|MODULE|OBJECT|INTERFACE|UNKNOWN>
IMPORTED [GLOBAL])
 Typically specify the library type as
UNKNOWN
 Set target properties to specify usage
requirements
 IMPORTED_CONFIGURATIONS
 IMPORTED_IMPLIB
 IMPORTED_IMPLIB_<CONFIG>
 IMPORTED_LINK_DEPENDENT_LIBRARIES
 IMPORTED_LINK_DEPENDENT_LIBRARIES_<CONFIG>
 IMPORTED_LINK_INTERFACE_LANGUAGES
 IMPORTED_LINK_INTERFACE_LANGUAGES_<CONFIG>
 IMPORTED_LINK_INTERFACE_LIBRARIES
 IMPORTED_LINK_INTERFACE_LIBRARIES_<CONFIG>
 IMPORTED_LOCATION
 IMPORTED_LOCATION_<CONFIG>
 INTERFACE_COMPILE_DEFINITIONS
 INTERFACE_COMPILE_FEATURES
 INTERFACE_COMPILE_OPTIONS
 INTERFACE_INCLUDE_DIRECTORIES
 INTERFACE_LINK_DIRECTORIES
 INTERFACE_LINK_LIBRARIES
 INTERFACE_LINK_OPTIONS
Relevant Target Properties
 Prefer target_XXX commands over setting
the properties directly
 set_target_properties will replace target
property settings with new values (it does
not append)
 set_property(TARGET) can be used to
append values to properties
Setting Target Properties
 Header only library
 Look for catch.hpp
 Create imported target Catch2::Catch
Example: Catch2 Unit Testing
Library
find_package(PkgConfig)
pkg_check_modules(PC_Catch2 QUIET catch)
find_path(Catch2_INCLUDE_DIR
NAMES catch.hpp
PATHS ${PC_Catch2_INCLUDE_DIRS})
find_package(PackageHandleStandardArgs REQUIRED)
find_package_handle_standard_args(Catch2
FOUND_VAR Catch2_FOUND
REQUIRED_VARS Catch2_INCLUDE_DIR)
if(Catch2_FOUND AND NOT TARGET Catch2::Catch)
add_library(Catch2::Catch INTERFACE IMPORTED)
set_target_properties(Catch2::Catch PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES
${Catch2_INCLUDE_DIR})
endif()
Example: Catch2 Unit Testing
Library
rd /s/q build
mkdir build
pushd build
cmake -G "Visual Studio 15 2017" ^
-DCMAKE_INCLUDE_PATH:PATH=C:/code/catch2/include ^
../source
popd
Example: Building with Catch2

More Related Content

What's hot

소프트박스 라즈베리파이 교육키트 개발환경 설정
소프트박스 라즈베리파이 교육키트 개발환경 설정소프트박스 라즈베리파이 교육키트 개발환경 설정
소프트박스 라즈베리파이 교육키트 개발환경 설정
봉조 김
 
Sharded Redis With Sentinel Vs Redis Cluster: What We Learned: Patrick King
Sharded Redis With Sentinel Vs Redis Cluster: What We Learned: Patrick KingSharded Redis With Sentinel Vs Redis Cluster: What We Learned: Patrick King
Sharded Redis With Sentinel Vs Redis Cluster: What We Learned: Patrick King
Redis Labs
 
Docker Advanced registry usage
Docker Advanced registry usageDocker Advanced registry usage
Docker Advanced registry usage
Docker, Inc.
 
HDFS Selective Wire Encryption
HDFS Selective Wire EncryptionHDFS Selective Wire Encryption
HDFS Selective Wire Encryption
Konstantin V. Shvachko
 
2021 04-20 apache arrow and its impact on the database industry.pptx
2021 04-20  apache arrow and its impact on the database industry.pptx2021 04-20  apache arrow and its impact on the database industry.pptx
2021 04-20 apache arrow and its impact on the database industry.pptx
Andrew Lamb
 
Respostas exercício 1 bdi
Respostas exercício 1   bdiRespostas exercício 1   bdi
Respostas exercício 1 bdi
Patty Muniz
 
Apresentação sobre Árvores B
Apresentação sobre Árvores BApresentação sobre Árvores B
Apresentação sobre Árvores B
Thiago Colares
 
Linux And perl
Linux And perlLinux And perl
Linux And perl
Sagar Kumar
 
Apostila de Banco dados
Apostila de Banco dadosApostila de Banco dados
Apostila de Banco dados
Fernando Palma
 
Iptables the Linux Firewall
Iptables the Linux Firewall Iptables the Linux Firewall
Iptables the Linux Firewall
Syed fawad Gillani
 
MongoDB (Advanced)
MongoDB (Advanced)MongoDB (Advanced)
MongoDB (Advanced)
TO THE NEW | Technology
 
Servidor DNS Ubuntu
Servidor DNS UbuntuServidor DNS Ubuntu
Servidor DNS Ubuntu
Sergio Santos
 
Windows 2008 MSCS 설치 가이드
Windows 2008 MSCS 설치 가이드Windows 2008 MSCS 설치 가이드
Windows 2008 MSCS 설치 가이드
CheolHee Han
 
A crash course in CRUSH
A crash course in CRUSHA crash course in CRUSH
A crash course in CRUSH
Sage Weil
 
Containerization and Docker
Containerization and DockerContainerization and Docker
Containerization and Docker
Megha Bansal
 
Users and groups in Linux
Users and groups in LinuxUsers and groups in Linux
Users and groups in Linux
Knoldus Inc.
 
Deploying IPv6 on OpenStack
Deploying IPv6 on OpenStackDeploying IPv6 on OpenStack
Deploying IPv6 on OpenStack
Vietnam Open Infrastructure User Group
 
Docker Containers Deep Dive
Docker Containers Deep DiveDocker Containers Deep Dive
Docker Containers Deep Dive
Will Kinard
 
Curso de Node JS Básico
Curso de Node JS BásicoCurso de Node JS Básico
Curso de Node JS Básico
Victor Hazin da Rocha
 
oVirt installation guide_v4.3
oVirt installation guide_v4.3oVirt installation guide_v4.3
oVirt installation guide_v4.3
CheolHee Han
 

What's hot (20)

소프트박스 라즈베리파이 교육키트 개발환경 설정
소프트박스 라즈베리파이 교육키트 개발환경 설정소프트박스 라즈베리파이 교육키트 개발환경 설정
소프트박스 라즈베리파이 교육키트 개발환경 설정
 
Sharded Redis With Sentinel Vs Redis Cluster: What We Learned: Patrick King
Sharded Redis With Sentinel Vs Redis Cluster: What We Learned: Patrick KingSharded Redis With Sentinel Vs Redis Cluster: What We Learned: Patrick King
Sharded Redis With Sentinel Vs Redis Cluster: What We Learned: Patrick King
 
Docker Advanced registry usage
Docker Advanced registry usageDocker Advanced registry usage
Docker Advanced registry usage
 
HDFS Selective Wire Encryption
HDFS Selective Wire EncryptionHDFS Selective Wire Encryption
HDFS Selective Wire Encryption
 
2021 04-20 apache arrow and its impact on the database industry.pptx
2021 04-20  apache arrow and its impact on the database industry.pptx2021 04-20  apache arrow and its impact on the database industry.pptx
2021 04-20 apache arrow and its impact on the database industry.pptx
 
Respostas exercício 1 bdi
Respostas exercício 1   bdiRespostas exercício 1   bdi
Respostas exercício 1 bdi
 
Apresentação sobre Árvores B
Apresentação sobre Árvores BApresentação sobre Árvores B
Apresentação sobre Árvores B
 
Linux And perl
Linux And perlLinux And perl
Linux And perl
 
Apostila de Banco dados
Apostila de Banco dadosApostila de Banco dados
Apostila de Banco dados
 
Iptables the Linux Firewall
Iptables the Linux Firewall Iptables the Linux Firewall
Iptables the Linux Firewall
 
MongoDB (Advanced)
MongoDB (Advanced)MongoDB (Advanced)
MongoDB (Advanced)
 
Servidor DNS Ubuntu
Servidor DNS UbuntuServidor DNS Ubuntu
Servidor DNS Ubuntu
 
Windows 2008 MSCS 설치 가이드
Windows 2008 MSCS 설치 가이드Windows 2008 MSCS 설치 가이드
Windows 2008 MSCS 설치 가이드
 
A crash course in CRUSH
A crash course in CRUSHA crash course in CRUSH
A crash course in CRUSH
 
Containerization and Docker
Containerization and DockerContainerization and Docker
Containerization and Docker
 
Users and groups in Linux
Users and groups in LinuxUsers and groups in Linux
Users and groups in Linux
 
Deploying IPv6 on OpenStack
Deploying IPv6 on OpenStackDeploying IPv6 on OpenStack
Deploying IPv6 on OpenStack
 
Docker Containers Deep Dive
Docker Containers Deep DiveDocker Containers Deep Dive
Docker Containers Deep Dive
 
Curso de Node JS Básico
Curso de Node JS BásicoCurso de Node JS Básico
Curso de Node JS Básico
 
oVirt installation guide_v4.3
oVirt installation guide_v4.3oVirt installation guide_v4.3
oVirt installation guide_v4.3
 

Similar to Consuming Libraries with CMake

Wiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingWiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programming
AnalyticsConf
 
dylibencapsulation
dylibencapsulationdylibencapsulation
dylibencapsulation
Cole Herzog
 
Power tools in Java
Power tools in JavaPower tools in Java
Power tools in Java
DPC Consulting Ltd
 
Why Drupal is Rockstar?
Why Drupal is Rockstar?Why Drupal is Rockstar?
Why Drupal is Rockstar?
Gerald Villorente
 
LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdf
Thninh2
 
Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++
Richard Thomson
 
Writing documentation with Asciidoctor
Writing documentation  with  AsciidoctorWriting documentation  with  Asciidoctor
Writing documentation with Asciidoctor
Jérémie Bresson
 
Object Oriented Programming - Java
Object Oriented Programming -  JavaObject Oriented Programming -  Java
Object Oriented Programming - Java
Daniel Ilunga
 
Operating System Practice : Meeting 4 - operasi file dan struktur direktori-s...
Operating System Practice : Meeting 4 - operasi file dan struktur direktori-s...Operating System Practice : Meeting 4 - operasi file dan struktur direktori-s...
Operating System Practice : Meeting 4 - operasi file dan struktur direktori-s...
Syaiful Ahdan
 
WhatsNewNIO2.pdf
WhatsNewNIO2.pdfWhatsNewNIO2.pdf
WhatsNewNIO2.pdf
Mohit Kumar
 
Effective CMake
Effective CMakeEffective CMake
Effective CMake
Daniel Pfeifer
 
CustomizingStyleSheetsForHTMLOutputs
CustomizingStyleSheetsForHTMLOutputsCustomizingStyleSheetsForHTMLOutputs
CustomizingStyleSheetsForHTMLOutputs
Suite Solutions
 
Best practices tekx
Best practices tekxBest practices tekx
Best practices tekx
Lorna Mitchell
 
Basic Make
Basic MakeBasic Make
Basic Make
Alec Clews
 
Autoconf&Automake
Autoconf&AutomakeAutoconf&Automake
Autoconf&Automake
niurui
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHP
Paul Jones
 
Feature and platform testing with CMake
Feature and platform testing with CMakeFeature and platform testing with CMake
Feature and platform testing with CMake
Richard Thomson
 
PyFilesystem
PyFilesystemPyFilesystem
PyFilesystem
Andreas Jung
 
Chapter 1 :
Chapter 1 : Chapter 1 :
Chapter 1 :
It Academy
 
CodeIgniter & MVC
CodeIgniter & MVCCodeIgniter & MVC
CodeIgniter & MVC
Jamshid Hashimi
 

Similar to Consuming Libraries with CMake (20)

Wiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingWiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programming
 
dylibencapsulation
dylibencapsulationdylibencapsulation
dylibencapsulation
 
Power tools in Java
Power tools in JavaPower tools in Java
Power tools in Java
 
Why Drupal is Rockstar?
Why Drupal is Rockstar?Why Drupal is Rockstar?
Why Drupal is Rockstar?
 
LOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdfLOSS_C11- Programming Linux 20221006.pdf
LOSS_C11- Programming Linux 20221006.pdf
 
Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++Consuming and Creating Libraries in C++
Consuming and Creating Libraries in C++
 
Writing documentation with Asciidoctor
Writing documentation  with  AsciidoctorWriting documentation  with  Asciidoctor
Writing documentation with Asciidoctor
 
Object Oriented Programming - Java
Object Oriented Programming -  JavaObject Oriented Programming -  Java
Object Oriented Programming - Java
 
Operating System Practice : Meeting 4 - operasi file dan struktur direktori-s...
Operating System Practice : Meeting 4 - operasi file dan struktur direktori-s...Operating System Practice : Meeting 4 - operasi file dan struktur direktori-s...
Operating System Practice : Meeting 4 - operasi file dan struktur direktori-s...
 
WhatsNewNIO2.pdf
WhatsNewNIO2.pdfWhatsNewNIO2.pdf
WhatsNewNIO2.pdf
 
Effective CMake
Effective CMakeEffective CMake
Effective CMake
 
CustomizingStyleSheetsForHTMLOutputs
CustomizingStyleSheetsForHTMLOutputsCustomizingStyleSheetsForHTMLOutputs
CustomizingStyleSheetsForHTMLOutputs
 
Best practices tekx
Best practices tekxBest practices tekx
Best practices tekx
 
Basic Make
Basic MakeBasic Make
Basic Make
 
Autoconf&Automake
Autoconf&AutomakeAutoconf&Automake
Autoconf&Automake
 
Decoupled Libraries for PHP
Decoupled Libraries for PHPDecoupled Libraries for PHP
Decoupled Libraries for PHP
 
Feature and platform testing with CMake
Feature and platform testing with CMakeFeature and platform testing with CMake
Feature and platform testing with CMake
 
PyFilesystem
PyFilesystemPyFilesystem
PyFilesystem
 
Chapter 1 :
Chapter 1 : Chapter 1 :
Chapter 1 :
 
CodeIgniter & MVC
CodeIgniter & MVCCodeIgniter & MVC
CodeIgniter & MVC
 

More from Richard Thomson

Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdfVintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
Richard Thomson
 
Automated Testing with CMake, CTest and CDash
Automated Testing with CMake, CTest and CDashAutomated Testing with CMake, CTest and CDash
Automated Testing with CMake, CTest and CDash
Richard Thomson
 
BEFLIX
BEFLIXBEFLIX
SIMD Processing Using Compiler Intrinsics
SIMD Processing Using Compiler IntrinsicsSIMD Processing Using Compiler Intrinsics
SIMD Processing Using Compiler Intrinsics
Richard Thomson
 
Modern C++
Modern C++Modern C++
Modern C++
Richard Thomson
 
Cross Platform Mobile Development with Visual Studio 2015 and C++
Cross Platform Mobile Development with Visual Studio 2015 and C++Cross Platform Mobile Development with Visual Studio 2015 and C++
Cross Platform Mobile Development with Visual Studio 2015 and C++
Richard Thomson
 
Web mashups with NodeJS
Web mashups with NodeJSWeb mashups with NodeJS
Web mashups with NodeJS
Richard Thomson
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmers
Richard Thomson
 

More from Richard Thomson (8)

Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdfVintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
Vintage Computing Festival Midwest 18 2023-09-09 What's In A Terminal.pdf
 
Automated Testing with CMake, CTest and CDash
Automated Testing with CMake, CTest and CDashAutomated Testing with CMake, CTest and CDash
Automated Testing with CMake, CTest and CDash
 
BEFLIX
BEFLIXBEFLIX
BEFLIX
 
SIMD Processing Using Compiler Intrinsics
SIMD Processing Using Compiler IntrinsicsSIMD Processing Using Compiler Intrinsics
SIMD Processing Using Compiler Intrinsics
 
Modern C++
Modern C++Modern C++
Modern C++
 
Cross Platform Mobile Development with Visual Studio 2015 and C++
Cross Platform Mobile Development with Visual Studio 2015 and C++Cross Platform Mobile Development with Visual Studio 2015 and C++
Cross Platform Mobile Development with Visual Studio 2015 and C++
 
Web mashups with NodeJS
Web mashups with NodeJSWeb mashups with NodeJS
Web mashups with NodeJS
 
C traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmersC traps and pitfalls for C++ programmers
C traps and pitfalls for C++ programmers
 

Recently uploaded

Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
lorraineandreiamcidl
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 

Recently uploaded (20)

Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptxLORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
LORRAINE ANDREI_LEQUIGAN_HOW TO USE WHATSAPP.pptx
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 

Consuming Libraries with CMake

  • 1. Richard Thomson Senior Software Engineer, NVIDIA @LegalizeAdulthd http://LegalizeAdulthood.wordpress.com legalize@xmission.com
  • 2. Outline  Review of C++ Libraries  find_package  pkg-config  Custom Find Module
  • 3. C++ Library Review  Source files include library headers  Executable linked against libraries
  • 4. Library Header Complications  May include headers from other libraries  May require specific preprocessor definitions  May have different names on different platforms  May have different names based on build configuration
  • 5. Library Link Complications  May depend on other libraries  May require specific runtime constraints, e.g. Windows C/C++ runtime library variants  May have different names on different platforms  May have different names based on build configuration  Library location may depend on build configuration
  • 6. CMake Requirements  Build Requirements  What is needed to build this target?  Usage Requirements  What is needed to use a target?  Requirement examples: ○ Compilation flags ○ Preprocessor definitions ○ Include directories ○ Link directories ○ Link dependencies  Requirements are propagated transitively by CMake between targets
  • 7. CMake Target Requirements  PRIVATE  Build requirements for the target  Imposes no usage requirement  INTERFACE  Usage requirements for the target  Imposes no build requirements  PUBLIC  Combination of PRIVATE and INTERFACE  Imposes build and usage requirements
  • 8. CMake Properties  A property is a name/value pair  CMake properties:  Global properties  Project properties  Directory properties  Target properties  Source file properties  Build requirements are properties  Usage requirements are properties
  • 9. CMake Modules  A module is just a text file containing CMake commands  Typically a module defines functions and macros  Usually named XXX.cmake  include(XXX) loads the module XXX.cmake  CMake has a module search path used to locate module files
  • 10. Imported Targets  Imported targets supply usage requirements  A find module may create imported targets for the found library  Usage requirements are associated with the imported target via target properties  Prefer imported targets for found libraries
  • 11. Library Flavors  Header Only Library  Static Library  Dynamic Library  Plug-In Library
  • 12. Header Only Library  Implementation exists only as headers  Library dependencies are linked into the executable  Executable and library must use compatible compilation flags  Unused code may be detected by the linker
  • 13. Header Only Library by Hand cmake_minimum_required(VERSION 3.16) project(hello VERSION 1.0 LANGUAGES CXX) add_executable(hello hello.cpp) target_compile_options(hello PRIVATE –Wall) target_compile_definitions(hello PRIVATE HAVE_IOSTREAMS) target_include_directories(hello PRIVATE greet/include)
  • 14. Static Library  Binds object code into the executable  Library dependencies are linked into the executable  Executable and library must use compatible compilation flags  Unused code may be detected by the linker
  • 15. Static Library by Hand cmake_minimum_required(VERSION 3.16) project(hello VERSION 1.0 LANGUAGES CXX) add_executable(hello hello.cpp) target_compile_options(hello PRIVATE –Wall) target_compile_definitions(hello PRIVATE HAVE_IOSTREAMS) target_include_directories(hello PRIVATE greet/include) target_link_libraries(hello PRIVATE greet/lib/libgreet.a)
  • 16. Dynamic Library  Binds references into the executable  Must be deployed with the executable  Library may be versioned  Executable and library must use compatible compilation flags
  • 17. Dynamic Library by Hand cmake_minimum_required(VERSION 3.16) project(hello VERSION 1.0 LANGUAGES CXX) add_executable(hello hello.cpp) target_compile_options(hello PRIVATE –Wall) target_compile_definitions(hello PRIVATE HAVE_IOSTREAMS) target_include_directories(hello PRIVATE greet/include) target_link_libraries(hello PRIVATE greet/lib/libgreet.so)
  • 18. Plug-In Library  Dynamic library that is accessed at runtime  Executable does not directly bind to the library  Executable queries plug-in for function entry points  Executable and library must use compatible compilation flags
  • 19. Plug-In Library by Hand cmake_minimum_required(VERSION 3.16) project(hello VERSION 1.0 LANGUAGES CXX) add_executable(hello hello.cpp) target_compile_options(hello PRIVATE –Wall) target_compile_definitions(hello PRIVATE HAVE_IOSTREAMS) target_include_directories(hello PRIVATE greet/include)
  • 20. Library by Hand Shortcomings  Consuming executable littered with library implementation details  Compilation options are compiler specific  Location of headers is assumed  Location of library is assumed  Doesn’t select debug or release library  Name of library is assumed
  • 21. find_package find_package(<PackageName> [version] [EXACT] [QUIET] [MODULE] [REQUIRED] [[COMPONENTS] [components...]] [OPTIONAL_COMPONENTS components...] [NO_POLICY_SCOPE])  Finds and loads settings from an external project  Sets <PackageName>_FOUND if found  Sucess results in variables and imported targets describing the found package  Unifies header only, static and dynamic libraries
  • 22. Find Modules  find_package looks for a Find Module for the requested package  The CMake module search path is used to located the Find Module  A Find Module is named FindXXX.cmake  CMake ships with many find modules
  • 23. find_package Example cmake_minimum_required(VERSION 3.16) project(hello VERSION 1.0 LANGUAGES CXX) add_executable(hello hello.cpp) find_package(Greeting 1.0 REQUIRED) target_link_libraries(hello PRIVATE Greeting::greet)
  • 24. pkg-config  pkg-config originated in Unix, but is available for Unix, macOS and Windows  pkg-config describes usage requirements for installed libraries  CMake’s FindPkgConfig module can create imported targets for pkg-config libraries
  • 25. pkg-config Example cmake_minimum_required(VERSION 3.16) project(hello VERSION 1.0 LANGUAGES CXX) find_package(PkgConfig REQUIRED) add_executable(hello hello.cpp) pkg_check_modules(Greeting REQUIRED IMPORTED_TARGET greet=1.0) target_link_libraries(hello PRIVATE PkgConfig::Greeting)
  • 26. Custom Find Module  Write your own find module when CMake has no find module for the library  Determines usage requirements:  Compile options  Compile definitions  Include directories  Link options  Link directories  Library filename  Create imported target(s) for the library
  • 27. Find Module Outline 1. Input data is described by find_package 2. Locate header files 3. Locate library files 4. Locate dependencies 5. Call find_package_handle_standard_args to communicate results to find_package 6. If everything found: 1. Create imported target 2. Set target properties
  • 28. Finding Things  find_file  find_program  find_path  find_library  find_package
  • 29. find_file find_file(<var> name | NAMES name1 [name2...] [HINTS path1 [path2...ENV var]] [PATHS path1 [path2...ENV var]] [PATH_SUFFIXES suffix1 [suffix2 ...]] [DOC "cache documentation string"] [NO_DEFAULT_PATH])  Locates a file according to name, location, suffix  Stores the result in <var>  Consult documentation for more options and details on search behavior
  • 30. find_program find_program(<var> name | NAMES name1 [name2...] [HINTS path1 [path2...ENV var]] [PATHS path1 [path2...ENV var]] [PATH_SUFFIXES suffix1 [suffix2 ...]] [DOC "cache documentation string"] [NO_DEFAULT_PATH])  Similar to find_file  Locates an executable program  Handles platform specific conventions, e.g. foo.exe on Windows
  • 31. find_path find_path(<var> name | NAMES name1 [name2...] [HINTS path1 [path2...ENV var]] [PATHS path1 [path2...ENV var]] [PATH_SUFFIXES suffix1 [suffix2 ...]] [DOC "cache documentation string"] [NO_DEFAULT_PATH])  Similar to find_file  Locates a directory containing a file
  • 32. find_library find_library(<var> name | NAMES name1 [name2...] [HINTS path1 [path2...ENV var]] [PATHS path1 [path2...ENV var]] [PATH_SUFFIXES suffix1 [suffix2 ...]] [DOC "cache documentation string"] [NO_DEFAULT_PATH])  Similar to find_file  Handles platform specific library forms, e.g. libfoo.a, foo.dll, foo.lib
  • 33.  Use find_package to locate your dependencies find_package
  • 34. find_package_handle_standard_ar gs find_package_handle_standard_args(<PackageName> [FOUND_VAR <result-var>] [REQUIRED_VARS <required-var>...] [VERSION_VAR <version-var>] [HANDLE_COMPONENTS] [CONFIG_MODE] [REASON_FAILURE_MESSAGE <message>] [FAIL_MESSAGE <message>] )  find_package(PackageHandleStandardArgs)  Use REQUIRED_VARS to list requirements: found files, directories, libraries, etc.  Combined result is in <result-var>
  • 35. Creating Imported Targets add_library(<name> <SHARED|STATIC|MODULE|OBJECT|INTERFACE|UNKNOWN> IMPORTED [GLOBAL])  Typically specify the library type as UNKNOWN  Set target properties to specify usage requirements
  • 36.  IMPORTED_CONFIGURATIONS  IMPORTED_IMPLIB  IMPORTED_IMPLIB_<CONFIG>  IMPORTED_LINK_DEPENDENT_LIBRARIES  IMPORTED_LINK_DEPENDENT_LIBRARIES_<CONFIG>  IMPORTED_LINK_INTERFACE_LANGUAGES  IMPORTED_LINK_INTERFACE_LANGUAGES_<CONFIG>  IMPORTED_LINK_INTERFACE_LIBRARIES  IMPORTED_LINK_INTERFACE_LIBRARIES_<CONFIG>  IMPORTED_LOCATION  IMPORTED_LOCATION_<CONFIG>  INTERFACE_COMPILE_DEFINITIONS  INTERFACE_COMPILE_FEATURES  INTERFACE_COMPILE_OPTIONS  INTERFACE_INCLUDE_DIRECTORIES  INTERFACE_LINK_DIRECTORIES  INTERFACE_LINK_LIBRARIES  INTERFACE_LINK_OPTIONS Relevant Target Properties
  • 37.  Prefer target_XXX commands over setting the properties directly  set_target_properties will replace target property settings with new values (it does not append)  set_property(TARGET) can be used to append values to properties Setting Target Properties
  • 38.  Header only library  Look for catch.hpp  Create imported target Catch2::Catch Example: Catch2 Unit Testing Library
  • 39. find_package(PkgConfig) pkg_check_modules(PC_Catch2 QUIET catch) find_path(Catch2_INCLUDE_DIR NAMES catch.hpp PATHS ${PC_Catch2_INCLUDE_DIRS}) find_package(PackageHandleStandardArgs REQUIRED) find_package_handle_standard_args(Catch2 FOUND_VAR Catch2_FOUND REQUIRED_VARS Catch2_INCLUDE_DIR) if(Catch2_FOUND AND NOT TARGET Catch2::Catch) add_library(Catch2::Catch INTERFACE IMPORTED) set_target_properties(Catch2::Catch PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${Catch2_INCLUDE_DIR}) endif() Example: Catch2 Unit Testing Library
  • 40. rd /s/q build mkdir build pushd build cmake -G "Visual Studio 15 2017" ^ -DCMAKE_INCLUDE_PATH:PATH=C:/code/catch2/include ^ ../source popd Example: Building with Catch2