CMake, CTest, CPack, CDash Package Software Open Source .

Transcription

CMake && FriendsOpen source tools to build, test andpackage softwareCMake, CTest, CPack, CDash1

CMake && FriendsOpen source tools to build, test andpackage softwareCMake, CTest, CPack, CDash2

PrefaceANL has CMake on Theta and CooleyCMake can be acquired from numerous locations for your localmachinehttps://www.cmake.org/download/From your Linux distributionVisual Studio 2017 apt.kitware.com for Debian and UbuntuSnap universal linux packagepip install cmakehomebrew3

PrefaceYou will need to install the exercisesDownload at: ANL resource4

5

Collaborative software R&DSOFTWAREPROCESSTechnical computingAlgorithms & applicationsSoftware process & infrastructureSupport & trainingOpen source leadership6

Successful small businessFounded in 1998; privately owned; no debt170 employees; 1/3 masters, 1/3 PhD 31M revenue in 2018AwardsHPC Best visualization productTibbetts award for outstanding research6-Time Inc. 5000 Honoree7

Supporting all sectorsSOFTWAREPROCESS75 Academic institutions50 Government agencies and labs100 Enterprises8

Open source platforms VTK & ParaView interactive visualization andanalysis for scientific data ITK & 3D Slicer medical image analysis andpersonalized medicine research CMake cross-platform build system– CDash, CTest, CPack, software process tools Resonant informatics and infovis KWIVER computer vision image and videoanalysisSimulation, ultrasound, physiology, informationsecurity, materials science, 9

Introduction to CMake10

What is a Build System?In the beginning there was the command line:% gcc hello.cxx -o hello

What is a Build System?Maybe use a shell script to avoid typingbuildhello.sh#!/bin/shgcc hello.cxx -o hello% buildhello.sh

What is a Build System?Even better use the make toolMakefilehello: hello.cxxgcc hello.cxx% make hello// what about #include files?

What is a Build System?Shell scriptsand commandlines andsimplemakefiles workfor a few files,but not for lotsof files like VTK

What is a Build System?A build system manages all of the sourcefiles and the complicatedinterdependencies for a project and turnsthem into hopefully useful programs andlibraries.

What is CMake? CMake is the cross-platform, open-source build system that lets you usethe native development tools you love the most. It’s a build system generator It takes plain text files as input that describe your project and producesproject files or make files for use with a wide variety of nativedevelopment tools. Family of Software Development Tools– Build CMakeTest CTest/CDashPackage CPack16

How CMake Changes The Way We Build C Boost aims to give C a set of useful libraries likeJava, Python, and C# CMake aims to give C compile portability like thecompile once and run everywhere of Java, Python, andC#– Same build tool and files for all platforms– Easy to mix both large and small libraries17

Where did CMake come from?

Where did CMake come from? Kitware was the lead engineering team forthe Insight Segmentation and RegistrationToolkit (ITK) http://www.itk.org Funded by National Library of Medicine(NLM): part of the Visible Human Project– Data CT/MR/Slice 1994/1995– Code (ITK) 1999

CMake: History Other available tools were insufficient: pcmaker (vtk3.2), autoconf,Apache ANT, qmake (Qt), JAM CMake provides the combination of native build tool use and platformintrospection that none of the others provide. CMake Release-1-0 branch created in 2001CMake 2.8 released in November, 2009CMake 3.0 released June, 2014CMake 3.14 released March, 2019CMake 3.17 released March, 202020

CMake has high adoption5 million CMake downloadsin 2019. 13809 downloadsper day, or a daily rate of307.3GiB, and yearly over10TiB

Jetbrains IDE- CMake is the mostpopular build tool at 42%. Job openings requiring CMake experience, March, 2019 Indeed.com, 464 jobs,at Tesla Motors, DCS Corp, Mindsource, Quanergy, .LinkedIn.com, 486 jobs, atSamsung, Johnson Controls, Apple, Uber, Toyota, Microsoft .

Updated CMake TutorialA new series of guides provided with each CMakerelease to help with learning and using CMake.Fully-tested source code embedded in HTML docs23

Outsource your build to the CMakedevelopers A build systemthat just works A build systemthat is easy to usecross platform24Typical Project without CMake (curl) lsCHANGESRELEASE-NOTES curl-config.in missingCMakeacinclude.m4 curl-style.el mkinstalldirsCMakeLists.txtaclocal.m4 depcompnotesbuilddocsnotes COPYINGbuildconf includepackagesCVSbuildconf.bat install-sh g.guess libcurl.pc.in srcMakefile.amconfig.sub ltmain.shtestsMakefile.inconfigure m4vc6curl.dswREADMEconfigure.ac maketgz ls src/CMakeLists.txt Makefile.riscos curlsrc.dsp hugehelp.h version.hCVSMakefile.vc6 curlsrc.dsw macoswriteenv.cMakefile.Watcom Makefile.vc8 curlutil.c main.cwriteenv.hMakefile.amconfig-amigaos.h curlutil.h makefile.amiga writeout.cMakefile.b32 config-mac.h getpass.c makefile.dj writeout.hMakefile.inconfig-riscos.h getpass.h mkhelp.plMakefile.inc config-win32.h homedir.c setup.hMakefile.m32 config.h.inhomedir.h urlglob.cMakefile.netware curl.rchugehelp.c urlglob.h

CMake: Bridging C gaps Open-source cross-platform build manager using native tools––––Visual Studio 6, 2003, 2005, 2008, 2010, 2012, 2013, 2015, 2017, 2019Borland make, Nmake, Unix make, MSYS make, MinGW makeNinjaXcode IDE KateCLionSublime TextEclipseVisual Studio CodeEmacs and Vim syntax files can be found on the CMake Download page25

CMake: Bridging C gaps Operating Systems:– HPUX, IRIX, Linux, MacOS, Windows, QNX, SunOS, and others Allows for platform inspection––––ProgramsLibraries and Header filesPackagesDetermine hardware specifics like byte order Compiler Language Level Support– C, C , ObjC, ObjC , CSharp, CUDA, Fortran, Swift26

CMake: Bridging C gaps Support for complex custom commands such as:–Qt’s moc, VTK’s wrapping Static, shared, object, and module library support– including versions .so support Single input format for all platforms Create configured .h files27

CMake: Bridging C gaps Automatic dependency generation (C, C , CUDA,Fortran)– build a target in some directory, and everything thistarget depends on will be up-to-date Automatic re-execution of cmake at build time ifany cmake input file has changed Parallel builds User defined build directory28

CMake: Bridging C gapsColor and progress output for makeGraphviz output for visualizing dependency treesFull cross platform install() systemCompute link depend information, and chaining ofdependent libraries make help, make foo.o, make foo.i, make foo.s 29

CMake: Bridging C gaps Advanced RPATH handling– Support for chrpath, i.e. changing the RPATH withoutneed to actually link again Create OSX library frameworks and applicationbundles Extensive test suite and nightly builds/test onmany platforms Supports cross compilation30

Learning CMakeFor help or more information see:– Professional CMake by Craig Scott– Discourse forum https://discourse.cmake.org– Documentation https://www.cmake.org/cmake/help/latest/– Tutorial /index.html31

Running CMake cmake-gui (the Qt gui) ccmake (the terminal cli) cmake (non-interactive command line)32

CMake Workflow33

Step 0 - Run CMakeCooley:soft add cmake-3.17.3Theta:module load cmake/3.16.2module swap craype-mic-knl craype-broadwellRun cmake --version from the command lineRun ccmake or cmake-gui34

Basic CMake SyntaxThe CMake language consists of:Commands, Variables, and Commentscmake minimum required(VERSION 3.8)project(main)# require C 11 and don’t decay down to 98set(CMAKE CXX STANDARD 11)set(CMAKE CXX STANDARD REQUIRED True)add subdirectory(MathFunctions)add executable(main main.cxx)target link libraries(main MathFunctions)35

Basic CMake Syntax: examplesCommands may span multiple lines, but the commandname and the opening parenthesis must be on the mplicitFunction.cxx)36

CMake Commands Commands are documented online and within cmake itself:– ommands.7.html Commands may be uppercase or lowercase.add executable(main main.cxx)ADD EXECUTABLE(main main.cxx)Prefer LowercaseHistorical note: commands used to be all uppercase, earningCMake the affectionate nickname “SCREAMMake” Thankfully,those days are over!37

CMake Commands (Arguments) Command arguments are space separated Arguments are case sensitiveadd executable(main WIN32 main.cxx) Quoted arguments– A quoted argument is always exactly one value.– An unquoted argument splits on semicolons andremoves empty arguments.38

CMake Variables Variable names are case sensitiveset(LEAF valueA)set(leaf valueB)Creates two distinct variables named “LEAF” and “leaf” Names can only contain alpha-numerics and underscores– [A-Za-z0-9 ] CMake uses many variables that begin with “CMAKE ” – avoidthis naming convention (and establish your own) for CMakevariables specific to your project39

CMake VariablesCMake variables are stringsset(name myexe)# These two statements are equivalent to each other.set(srcs src1.cxx src2.cxx src3.cxx)set(srcs "src1.cxx;src2.cxx;src3.cxx")40

CMake VariablesSpecial syntax for setting environmentuse ENV and curly braces { }set(ENV{PATH} value .)41

CMake VariablesVariable dereferencing syntax: {VAR}message(STATUS "CMAKE SOURCE DIR ' {CMAKE SOURCE DIR}'")set(my dir " {CMAKE CURRENT SOURCE DIR}/my dir")message(STATUS "my dir ' {my dir}'")Environment Variable dereferencing syntax: ENV{VAR}set(my path " ENV{PATH}")message(STATUS "my path ' {my path}'")42

CMake VariablesEscaping \ is the escape character used in CMake You can also use long bracketsset(classic str "* here be \"dragons\" *")set(long brackets [ [* here be "dragons" *] ])message(STATUS {classic str})message(STATUS {long brackets})Both of these print: * here be "dragons" *43

Configuring Header Files Can put build parameters into a header fileinstead of passing them on the command lineconfigure file( {PROJECT SOURCE DIR}/projectConfig.h.in {PROJECT BINARY DIR}/projectConfig.h)44

Configuring Header Files #define VARIABLE @VARIABLE@// C source file#define VARIABLE @VARIABLE@#ifdef VARIABLE// will be hit when the CMake variable doesn't exist#endif45

Configuring Header Files #cmakedefine VARIABLE// C source file#cmakedefine @VARIABLE@#ifdef VARIABLE// will not-be hit when the CMake// variable doesn't exist#endif46

Requiring a CMake Version First line of the top level CMakeLists.txt should alwaysbe cmake minimum requiredcmake minimum required(VERSION 3.9)project(Example LANGUAGES C CXX CUDA) Allows projects to require a given version of CMake Allows CMake to be backwards compatible47

project() command Necessary for the top-level CMake. Should be set after thecmake minimum required commandcmake minimum required(VERSION 3.9)project(Example LANGUAGES C CXX CUDA) VERSION: sets the PROJECT VERSION MAJOR/MINOR/TWEAK DESCRIPTION: sets the PROJECT DESCRIPTION variable LANGUAGES:– C, CXX, FORTRAN, CSharp, CUDA, ASM– Default is C and CXX if not defined48

CMake Language Standards CMake offers a few different ways to specifywhich version of a language should be used.set(CMAKE CXX STANDARD 11)set(CMAKE CXX STANDARD REQUIRED TRUE)[ 50%] Building CXX object main.cxx.o/usr/bin/c -std gnu 11 -o main.cxx.o -c main.cxx CMAKE CXX EXTENSIONS controls ifcompiler specific extensions are enabled49

CMake 3.8: meta-features Request compiler modes for specific language standard levels– cxx std 11, cxx std 14, cxx std 17– Works with Clang, GCC, MSVC, Intel, Cray, PGI, XL These should be used instead of features like cxx auto type# Request that particles be built with -std c 17# As this is a public compile feature anything that links to particles# will also build with -std c 17target compile features(particles PUBLIC cxx std 17)50

Step 0.5 - CMake and Compiler SelectionCooley:soft add cmake-3.17.3Theta:module load cmake/3.16.2module swap craype-mic-knl craype-broadwell CMake caches the compiler for a build directory on the first invocation. CMake compiler detection has the following preference– env variables ( CC, CXX )– cc and cxx path entries– gcc and g path entries Try the following on cooley / theta– soft add gcc-7.1.0 [cooley only]– cmake -S Step0 -B Step0CXXBuildDir– CXX g cmake -S Step0 -B Step0GCCBuildDir51

Step 0.5 - CMake and Compiler Selection52

Step 1 - Configure a File and C 11 ControlsCooley:soft add cmake-3.17.3Theta:module load cmake/3.16.2module swap craype-mic-knl craype-broadwell Follow the instructions in Step1 Run cmake or cmake-gui to configure the project and then build it with yourchosen build tool cd to the directory where Tutorial was built (likely the make directory or aDebug or Release build configuration subdirectory) and run these commands:– Tutorial 4294967296– Tutorial 10– Tutorial53

Flow control (if)CMake if commandsupports a widerange of expressionsif(my var)set(result {my var})endif()if(NOT my var)if(my var AND my var2)if(my var OR my var2)if(my var MATCHES regexp)if(TARGET target)if(EXISTS file)if(my var LESS my var2)if(my ver VERSION EQUAL "2.0.2")54

Flow control (if): FALSE values The following values are all equivalent to “FALSE” ina CMake if command:––––––––“” (the empty string)OFF0NOFALSEN“NOTFOUND” exactly or ends in “-NOTFOUND”IGNORE55

Flow control: loopsforeach(F IN ITEMS a b c)message( {F})endforeach()while(MY VAR)message( {MY VAR})set(MY VAR FALSE)endwhile()set(items a b c)foreach(F IN LISTS items)message( {F})endforeach()56

add subdirectory and variable scope The add subdirectory command allows a projectto be separated into directories Variable values are inherited by CMakeLists.txtfiles in sub directories– TopDirset(MY VAR 1)add subdirectory(Dir1)– TopDir/Dir1Dir1/CMakeLists.txt- MY VAR is 157

Functionfunction(showcase args myarg)message("myarg: {myarg}")message("ARGV0: {ARGV0}")message("contents of myarg: { {myarg}}")message("extra arguments: {ARGN}")message("# of arguments: {ARGC}")endfunction()myarg: itemsARGV0: itemscontents of myarg: a;b;cextra arguments:# of arguments: 1set(items a b c)showcase args(items) ARGC – number of arguments passedARGV0, ARGV1, - actual parameters passed inARGV – list of all argumentsARGN – list of all arguments beyond the last formal parameter58

Function Dynamically scoped, so any variables set are local to thefunction Use set(.PARENT SCOPE) to set a variable in the callingscopefunction(showcase args myarg)set(" {myarg}" { {myarg}} d e f PARENT SCOPE)endfunction()set(items a b c)showcase args(items)message("items: {items}")items: a;b;c;d;e;f59

Macro Not dynamically scoped, so all variables leak intothe calling scopemacro(showcase args arg1)set(" {arg1}" { {arg1}} d e f)endmacro()set(items a b c)showcase args(items)message("items: {items}")items: a;b;c;d;e;f60

CMake Common Command Reviewcmake minimum required(VERSION 3.9)project(Example LANGUAGES C CXX)set(CMAKE CXX STANDARD 11)set(CMAKE CXX STANDARD REQUIRED xxImplicitFunctions.cxx)add library(simplelib {srcs})add executable(example main.cxx)target link libraries(examplePRIVATE simplelib)add subdirectory(tests)61

CMake Commands All commands– cmake --help-command-list– cmake --help-command command name– ommands.7.html62

CMakeCache.txt Stores optional choices and provides a project global variable repositoryVariables are kept from run to runLocated in the top directory of the build treeA set of entries like this:– KEY:TYPE VALUE Valid types:– BOOL– STRING– PATH– FILEPATH– INTERNAL(these are only used by cmake-gui and ccmake to display the appropriate typeof edit widget)63

CMake Cache//Sphinx Documentation Builder(sphinx-doc.org)SPHINX EXECUTABLE:FILEPATH C:/Python27/Scripts/sphinx-build.exe.//Build html help with SphinxSPHINX HTML:BOOL ON64

Variables and the Cache Use option command or set commandwith CACHE keywordoption(MY VAR "only bool var" TRUE)set(MY VAR TRUE CACHE BOOL "bool var")65

Variables and the CacheDereferences look first for a local variable, thenin the cache if there is no local definition for avariableLocal variables hide cache variables66

Variables and the CacheWhich one is the better option?set(CMAKE CXX FLAGS "-Wall")set(CMAKE CXX FLAGS " {CMAKE CXX FLAGS} -Wall")set(CMAKE CXX FLAGS "." CACHE STRING "" FORCE)67

Variables and the Cacheset(CMAKE CXX FLAGS "-Wall")# Clears any users CXX FLAGS! :(set(CMAKE CXX FLAGS " {CMAKE CXX FLAGS} -Wall")set(CMAKE CXX FLAGS "." CACHE STRING "" FORCE)# Will keep appending each time you reconfigure# the project68

mark as advanced Advanced variables are not displayed in thecache editors by default Allows for complicated, seldom changedoptions to be hidden from users Cache variables of the INTERNAL type arenever shown in cache editors69

CMake Special Variables cmake --help-variables or online docs User settable variables– BUILD SHARED LIBS– CMAKE INSTALL PREFIX– CMAKE CXX FLAGS / CMAKE LANG FLAGS CMake pre-defined variables (should not be set by user code)– WIN32, UNIX, APPLE, CMAKE VERSION– CMAKE SOURCE DIR, CMAKE BINARY DIR– PROJECT NAME– PROJECT SOURCE DIR, PROJECT BINARY DIR70

Passing options to the compileradd compile definitions(-Drevision 2902)target compile definitions(Tutorial PRIVATE revision 2902)target compile options(Tutorial PRIVATE -march native) alternative to configuring header files targets, directories, and source files have the properties:COMPILE OPTIONS, COMPILE DEFINITIONSWhich can be also be used instead of the target commands.71

Build Configurations With Makefile generators(Makefile, Ninja):– CMAKE BUILD TYPE:STRING Release– known values are: Debug, Release, MinSizeRel,RelWithDebInfo To build multiple configurations with a Makefilegenerator, use multiple build trees72

Build Configurations With multi-config generators (Visual Studio / Xcode):– CMAKE CONFIGURATION TYPES list of valid values for config types– All binaries go into config subdirectory {CMAKE CURRENT BINARY DIR}/bin/Debug/ {CMAKE CURRENT BINARY DIR}/bin/Release/73

Build Configurations To set per configuration information:– per target use CONFIG target compile definitions(Tutorial PRIVATE CONFIG:DEBUG :ENABLE DEBUG CHECKS )– globally use CMAKE CXX FLAGS CONFIG 74

Build Configurations To get the current configuration type frommulti-conf:– Generate Time: CONFIG – Build-time (deprecated): {CMAKE CFG INTDIR}– In source file CMAKE INTDIR which is defined automatically75

ADDING LIBRARIES76

CMake Libraries Use the add library command to build libraries.option(BUILD SHARED LIBS"controls add library default type" ON)add library(root root.cxx)add library(trunk STATIC trunk.cxx)add library(leaf SHARED leaf.cxx) STATIC .a or .lib archive SHARED .so, .dylib, or .dll dynamic library77

CMake Librariesoption(BUILD SHARED LIBS"controls add library default type" ON)add library(root root.cxx)add library(trunk STATIC trunk.cxx)add library(leaf SHARED leaf.cxx) SHARED will work on Unix where supported. SHARED on Windows requires code changes or *.deffiles to export symbols. CMake makes this easier.78

Linking to Libraries target link libraries is how youspecify what libraries a target requires.add library(root SHARED root.cxx)add library(trunk SHARED trunk.cxx)add library(leaf SHARED leaf.cxx)target link libraries(trunk root)target link libraries(leaf trunk)79

Linking to Libraries By default target link libraries istransitive[100%] Linking CXX shared library libleaf.so/usr/bin/c -fPIC -shared -Wl,-soname,libleaf.so-o libleaf.so leaf.cxx.o libtrunk.so libroot.so[100%] Built target leaf80

MODULE Libraries Very similar to SHARED libraries but are notlinked into other targets but can be loadeddynamically at runtime using dlopen-likefunctionalityadd library(parasite MODULE eat leaf.cxx)81

OBJECT Libraries Generate the object files but does notconstruct an archive or library––––Can be installed [3.9]Can be exported/imported [3.9]Can be consumed with target link libraries [3.12]Can have transitive information [3.12]82

OBJECT Librariesadd library(root OBJECT root.cxx)add library(trunk OBJECT trunk.cxx)add library(leaf SHARED leaf.cxx)target link libraries(leaf root trunk)[100%] Linking CXX shared library libleaf.so/usr/bin/c -fPIC-shared -Wl,-soname,libleaf.so-o libleaf.so leaf.cxx.o root.cxx.o trunk.cxx.o83

OBJECT Librariesadd library(root OBJECT root.cxx)add library(trunk OBJECT trunk.cxx)add library(leaf SHAREDleaf.cxx TARGET OBJECTS:root TARGET OBJECTS:trunk )[100%] Linking CXX shared library libleaf.so/usr/bin/c -fPIC-shared -Wl,-soname,libleaf.so-o libleaf.so leaf.cxx.o root.cxx.o trunk.cxx.o84

OBJECT Libraries Caveats CMake 3.9 added ability for OBJECT librariesto be:– Installed / Exported / Imported– TARGET OBJECTS to be used in moregenerator expression locations85

OBJECT Libraries Caveats CMake 3.12 added ability to link to OBJECTlibraries:– Will behave like any other library for propagation– Anything that links to an OBJECT library will havethe objects embedded into it.86

Step 2- Adding a libraryCooley:soft add cmake-3.17.3Theta:module load cmake/3.16.2module swap craype-mic-knl craype-broadwell Follow the directions in Step2 Run cmake or cmake-gui to configure the project and thenbuild it with your chosen build tool Run the built Tutorial executable Which function gives better results,– Step1’s sqrt or Step2’s mysqrt?87

Modern CMakeUSAGE REQUIREMENTS88

Before Usage Requirements Before Usage Requirements existedwe used directory scoped commandsDirectorysuch as:– include directoriesDirectoryDirectory– compile definitions– compile options Consumers have to know:– Does the dependency generateExecutableLibrary BLibrary Abuild tree files– Does the dependency use anynew external package89

Modern CMake / Usage Requirements Modern CMake goal is to have each targetfully describe how to properly use it No difference between using internal andexternal generated targets90

Modern eLibrary BLibrary ALibrary BLibrary ALibrary BLibrary AExecutableLibrary A91

Usage Requirements target link libraries is the foundation forusage requirements This foundation is formed by– PUBLIC– PRIVATE– INTERFACEtarget link libraries(trunk PRIVATE root)target link libraries(leaf PUBLIC trunk)92

Usage Requirementstarget link libraries(trunk root)target link libraries(leaf trunk)/usr/bin/c -fPIC -shared -Wl,-soname,libleaf.so-o libleaf.so leaf.cxx.o libtrunk.so libroot.sotarget link libraries(trunk PRIVATE root)target link libraries(leaf PUBLIC trunk)/usr/bin/c -fPIC -shared -Wl,-soname,libleaf.so-o libleaf.so leaf.cxx.o libtrunk.so93

TLL ( target link libraries) TLL can propagate dependencies when using:–––––target include directoriestarget compile definitionstarget compile optionstarget sourcestarget link options94

target include directories Propagates include directoriestarget include directories(leaf INTERFACE {zlib dir}) Anything that links to leaf will automaticallyhave the zlib dir on the include line95

target compile options Propagates compiler optionstarget compile options(trunk PRIVATE -march native) Only trunk will be built optimized for thecurrent hardware. Anything that links to trunkwill not get this flag96

target compile definitions Propagates pre-processor definitionstarget compile definitions(root PUBLIC "ROOT VERSION 42") Root will have ROOT VERSION defined andanything that links to it will also97

INTERFACE Libraries An INTERFACE library target does not directlycreate build output, though it may haveproperties set on it and it may be installed,exported, and imported.add library(root INTERFACE)target compile features(root INTERFACE cxx std 11)98

Step 3 - Usage Requirements for LibraryCooley:soft add cmake-3.17.3Theta:module load cmake/3.16.2module swap craype-mic-knl craype-broadwell Follow the directions in Step3 of the Tutorial Run cmake or cmake-gui to configure the projectand then build it with your chosen build tool99

INSTALL RULES100

Install Rules Specify rules to run at install time Can install targets, files, or directories Provides default install locationsadd library(leaf SHARED leaf.cxx)install(TARGETS root trunk leaf parasite)101

Install Targetsadd library(leaf SHARED leaf.cxx)install(TARGETS root trunk leaf parasite)add library(leaf SHARED leaf.cxx)install(TARGETS root trunk leaf parasiteARCHIVE DESTINATION libLIBRARY DESTINATION libRUNTIME DESTINATION bin)102

Install Targetsadd library(leaf SHARED leaf.cxx)install(TARGETS root trunk leaf parasite)Target TypeGNUInstallDirs VariableBuilt-in DefaultRUNTIME {CMAKE INSTALL BINDIR}binLIBRARY {CMAKE INSTALL LIBDIR}libARCHIVE {CMAKE INSTALL LIBDIR}libPRIVATE HEADER {CMAKE INSTALL INCLUDEDIR}includePUBLIC HEADER {CMAKE INSTALL INCLUDEDIR}include103

Install Filesinstall(FILEStrunk.hleaf.hDESTINATION {CMAKE INSTALL INCLUDEDIR}/tree)104

Install Filesadd library(leaf SHARED leaf.cxx)set target properties(leaf PROPERTIESPUBLIC HEADER leaf.h)install(TARGETS root trunk leaf parasitePUBLIC HEADER DESTINATION {CMAKE INSTALL INCLUDEDIR}/tree)105

Exporting Targets Install rules can generate imported targetsadd library(parasite STATIC eat leaf.cxx)install(TARGETS parasite root trunk leafEXPORT tree-targets)install(EXPORT tree-targetsDESTINATION lib/cmake/tree) Installs library and target import rules– prefix /lib/libparasite.a– prefix /lib/cmake/tree/tree-targets.cmake106

CTEST107

Testing with CMake Testing needs to be enabled by calling include(CTest) orenable testing()add test(NAME testnameCOMMAND exename arg1 arg2 .)– Executable should return 0 for a test that passes ctest – an executable that is distributed with cmake thatcan run tests in a project108

Running CTest Run ctest at the top of a binary directory to run all tests ctestTest projectStart 1:1/1 Test #1:Start 2:2/2 Test #2:/tmp/example/bincase1case1 .case2case2 .Passed0.00 secPassed0.00 sec100% tests passed, 0 tests failed out of 2Total Test time (real) 0.01 sec109

Running CTest -j option allows you to run tests in parallel-R option allows you to choose a test-VV for more verbose output--rerun-failed to repeat failed tests ctest --help for more information110

Test fixtures Attach setup and cleanup tasks to a set oftests. Setup tests “main” tests cleanup tests If any setup tests fail the “main” tests will notbe run. The cleanup tests are always executed, evenif some of the setup tests failed.111

Test Fixtures exampleadd test(NAME myDBTestCOMMAND testDb)add test(NAME createDBadd test(NAME setupUsersCOMMAND initDB)COMMAND userCreation)add test(NAME cleanupDBadd test(NAME testsDoneCOMMAND deleteDB)COMMAND emailResults)112

Test Fixtures exampleset tests properties(setupUsersDEPENDS createDB)set tests properties(createDBFIXTURES SETUPDB)set tests properties(setupUsersFIXTURES SETUPDB)set tests properties(cleanupDBFIXTURES CLEANUP DB)set tests properties(myDBTestFIXTURES REQUIRED IES113

GoogleTest integrationinclude(GoogleTest)add executable(tests tests.cpp)target link libraries(tests GTest::GTest) gtest discover tests: added in CMake 3.10.– CMake asks the test executable to list its tests.Finds new tests without rerunning CMake.gtest discover tests(tests)114

GoogleTest integrationinclude(GoogleTest)add executable(tests tests.cpp)target link libraries(tests GTest::GTest) gtest add tests: use for CMake 3.9.– Scans source files to finds tests. New tests areonly discovered when CMake re-runs.gtest add tests(TARGET tests)115

CTest and multi core tests When launching tests that use multi cores itis important to make sure you use thefollowing:set tests properties(myTest PROPERTIESPROCESSORS 4)116

CTest and multi core tests PROCESSOR AFFINITY - when supported tiesprocesses to specific processorsset tests properties(myTest PROPERTIESPROCESSOR AFFINITY ONPROCESSORS 4)117

Test Resource Allocation Tests specify the resources they need Users specify the resources available on themachine CTest keeps track of available resources whenrunning tests in parallel New in CMake v3.16118

Test Resource Allocation Tests using GPU– Run tests serially too slow– Run tests in parallel exhaust availablememory spurious failures Tests dictate how much GPU memory theyuse CTest can run tests in parallel withoutexhausting GPU memory119

Test Resource Allocation CTest does not directly communicate withGPUs It keeps track of abstract resource types andthe number of “slots” available120

Test Resource Allocation For tests, set RESOURCE GROUPS propertyset property(TEST MyTest PROPERTYRESOURCE GROUPS "gpus:2" "crypto chips:1") For machines, define a Resource SpecificationJSON file.ctest test(RESOURCE SPEC FILE spec.json)121

Step 4 - Installing and Testing Follow the directions in Step4 of the CMake Tutorial– Expect the make install to fail when on ANL hardware Run cmake or cmake-gui to configure the project and then build it withyour chosen build tool Build the “install” target (make install, or right click install and choose“Build Project”) – verify that the installed Tutorial runs cd to the binary directory

– Visual Studio 6, 2003, 2005, 2008, 2010, 2012, 2013, 2015, 2017, 2019 – Borland make, Nmake, Unix make, MSYS make, MinGW make – Ninja – Xcode IDE Support – Code::Blocks KDevelop – CodeLite Kate – CLion S