1

I want to use regular expression to add all files to add_library, but it does not work.

I tried this :

add_library(8021qbg SHARED
        8021QBG/"*.h"
        8021QBG/"*.cpp"
        )

And get this:

CMake Error at CMakeLists.txt:128 (add_library):
  Cannot find source file:

    8021QBG/"*.h"

  Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp
  .hxx .in .txx

I tried this:

file(GLOB 8021x
        8021x/"*.h"
        8021x/"*.cpp"
        )
add_library(8021x SHARED
        ${8021x}
        )

And at compiling make command does not see sources to compile.

I want to build shared library using something not to write down every source file (regular expression, I suppose).

How to do it?

YSC
  • 38,212
  • 9
  • 96
  • 149
user3360601
  • 327
  • 3
  • 17
  • just put quotes round the whole file path rather than just the filename? – Alan Birtles Aug 05 '19 at 09:19
  • @AlanBirtles, No working, the same error – user3360601 Aug 05 '19 at 09:20
  • Possible duplicate of [Automatically add all files in a folder to a target using CMake?](https://stackoverflow.com/questions/3201154/automatically-add-all-files-in-a-folder-to-a-target-using-cmake) – Alan Birtles Aug 05 '19 at 09:22
  • @AlanBirtles, I saw this post, I need not executable, but shared library. If there is some way to do it via add_executable command - how to do it? – user3360601 Aug 05 '19 at 09:23

2 Answers2

4

You need to ask cmake to list all matching files into a variable:

file(GLOB SOURCE_FILES
    8021QBG/*.h
    8021QBG/*.cpp
)

and then use this variable:

add_library(8021qbg SHARED
    ${SOURCE_FILES}
)

More on file(GLOB) command.

Generate a list of files that match the and store it into the . Globbing expressions are similar to regular expressions, but much simpler.

YSC
  • 38,212
  • 9
  • 96
  • 149
  • @YSC, thank you very much.This is one way that I know how to develop project on the host and build it remotely using IDE capabilities. – user3360601 Aug 05 '19 at 09:34
0

With the following addition cmake is able to determine the name of the lib being added thus making the script context agnostic.

# libname = current directory name
get_filename_component(libname "${CMAKE_CURRENT_SOURCE_DIR}" NAME)

# .c and .h files
file(GLOB thislibsrc ${CMAKE_CURRENT_SOURCE_DIR}/*.c ${CMAKE_CURRENT_SOURCE_DIR}/*.h)

# include it only once
include_guard(GLOBAL)

# and use it 
add_library(${libname} STATIC ${thislibsrc} )
...

I have such little components saved in some central directory so I can call them later like:

include(../addlibscr.cmake)