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.)
There's a convention for CMake modules: snake-case
function_or_macro()
is implemented in CamelCaseFunctionOrMacro.cmake
file. So when in doubt, use CamelCase.And use verbs, nouns are for classes.