2

In my cmake C++ project, I am adding source files to target by

file(GLOB HEADERS *.h)
file(GLOB SOURCES *.cpp)
add_library(${PROJECT_NAME} SHARED ${SOURCES} ${HEADERS})

In macOS this is including files like ._Source.cpp and ._Header.h I tried the REGEX

list(FILTER HEADERS REGEX "^[^\.].+" output_variable HEADERS)
list(FILTER SOURCES REGEX "^[^\.].+" output_variable SOURCES)

but this is not working.

Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
Necktwi
  • 2,483
  • 7
  • 39
  • 62
  • Isn't that `list(FILTER HEADERS INCLUDE REGEX "^[^\.].+")`? – Florian Feb 07 '17 at 08:15
  • @Florian This gave `list sub-command FILTER requires list to be present.` error – Necktwi Feb 07 '17 at 09:02
  • @Florian I have corrected the syntax but still `list(FILTER HEADERS EXCLUDE REGEX "^[\.].+")` has no effect. still `._` files are being included – Necktwi Feb 07 '17 at 09:16
  • `list(FILTER HEADERS EXCLUDE REGEX "^\\..+")`? I forgot that CMake needs double backslash, because it evaluates escape sequences first. – Florian Feb 07 '17 at 09:19
  • See also [here](http://stackoverflow.com/questions/4490793/cmake-how-to-get-the-backslash-literal-in-regexp-replace) – Florian Feb 07 '17 at 09:26
  • I have used backslash to escape `.` inside `[]`. doesn't it needed? – Necktwi Feb 07 '17 at 09:37
  • I don't think you need the `[]` (any-of-expression) because you only check for a single character. – Florian Feb 07 '17 at 09:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/135039/discussion-between-necktwi-and-florian). – Necktwi Feb 07 '17 at 09:52

1 Answers1

10

Turning my comments into an answer

file(GLOB HEADERS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "*.h") 
file(GLOB SOURCES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "*.cpp") 

list(FILTER HEADERS EXCLUDE REGEX "^\\..+") 
list(FILTER SOURCES EXCLUDE REGEX "^\\..+"
  • The list(FILTER ...) needs INCLUDE or EXCLUDE keyword
  • The file(GLOB ...) by default will return full paths, so you need to add the RELATIVE keyword
  • The regex needs double backslashs, because CMake evaluates escape sequences first
  • You don't need the [] (any-of-expression) because you only check for a single character

Reference

Community
  • 1
  • 1
Florian
  • 39,996
  • 9
  • 133
  • 149