What is the naming convention for CMake scripts?
Asked Answered
C

1

3

I know that CMake makes use of the standard name "CMakeLists.txt" and the add_subdirectory function for calling scripts directly in the build process.

I have some CMake code that I use to turn files into C++ strings that can then be baked into the program using #include directives. The relevant code in my root CMakeLists file looks like this (greatly simplified, of course):

add_custom_command(
  OUTPUT ${CMAKE_BINARY_DIR}/path/to/example.json.txt
  COMMAND ${CMAKE_COMMAND} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR} ${STRING_PATH} -P BuildString.cmake
  DEPENDS ${CMAKE_SOURCE_DIR}/path/to/example.json
  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
)
add_custom_target(strings DEPENDS ${CMAKE_BINARY_DIR}/path/to/example.json.txt)

(In the actual code, I call add_custom_command for each file I need to turn into a string, then pass all the output filenames as a list to add_custom_target.)

And here is BuildString.cmake:

set(DELIMITER "")

set(SOURCE ${CMAKE_ARGV1})
set(BUILD ${CMAKE_ARGV2})
set(PATH ${CMAKE_ARGV3})

file(READ ${SOURCE}/${PATH} STRING)
# add semicolons back into string
string(REGEX REPLACE ";" "\\\\;" STRING "${STRING}")
file(WRITE ${BUILD}/${PATH}.txt R\"${DELIMITER}\(${STRING}\)${DELIMITER}\")

As you can see, BuildString.cmake just takes an input file and outputs the contents of that file (wrapped in C++ raw string literal notation using ${DELIMITER} as the delimiter) into the build directory.

What should I call BuildString.cmake? Is the convention to use all lowercase with underscores (build_string.cmake), or maybe lower camel case (buildString.cmake)? Or should the name be a noun instead of a verb (StringBuilder.cmake)?

(As a side note, if you can see an unrelated way I could improve any of this code, that would also be appreciated.)

Chrystal answered 24/6, 2015 at 18:16 Comment(0)
S
5

There's a convention for CMake modules: snake-case function_or_macro() is implemented in CamelCase FunctionOrMacro.cmake file. So when in doubt, use CamelCase.

And use verbs, nouns are for classes.

Scab answered 30/6, 2015 at 13:45 Comment(2)
Yes, I have seen that convention used before. However, in this particular case, the script in question doesn't actually contain a function or macro; instead, it essentially "acts as" a function that is meant to be called at build time instead of at "CMake time". Does the same naming convention still apply?Chrystal
@RedRoboHood: All cmake and shell scripts shipping with CMake follow this convention (not only macros or functions). But since for scripts I don't think it is as strong as it is for function/macros defs, I would say, if you need a convention, use this one as there's no other. But feel free to name your scripts whatever you want. That's why I meant by "when in doubt".Scab

© 2022 - 2024 — McMap. All rights reserved.