cmake custom command to copy and rename
add_custom_target(CopyAndRename
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/test.so ${CMAKE_BINARY_DIR}/SomeThingElse.so
)
add_custom_target introduces a new target named CopyAndRename. You can run it with:
make CopyAndRename
I'd stick with your original idea of using add_custom_command
. However, I'd recommend you use the add_custom_command(TARGET ...)
form rather than add_custom_command(OUTPUT ...)
.
The OUTPUT
version is designed to have the output file used as a source file in a different CMake target in the same CMakeLists.txt. The custom command is invoked when this target is built (right at the start), since the target needs the file to exist at that point.
In your case, no target depends on your file - it's a product of the build process.
If you use add_custom_command(TARGET ...)
, this guarantees the command is executed every time the target is rebuilt. Using add_custom_target
requires you to remember to build this if the original target (test
in this case) is updated. It also needlessly adds to your list of targets - maybe not an issue for a tiny project, but it can be for larger projects.
Here's how I'd set up the command:
SET(COPY_TO_PATH custom1)
ADD_CUSTOM_COMMAND(TARGET test POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
$<TARGET_FILE:test>
${COPY_TO_PATH}
COMMENT "Copying 'test' library to '${COPY_TO_PATH}'")
This adds the command as a post-build event of test
's. As you rightly identified, hard-coding library names isn't great; hence CMake provides "generator expressions" to handle this. The generator expression $<TARGET_FILE:test>
resolves to the full path of the library created by test
, regardless of platform or compiler. Note that generator expressions can only be used in the COMMAND
argument; you couldn't use them in the COMMENT
part for example.
The actual command is invoking CMake itself (${CMAKE_COMMAND}
) with its -E
command line option. This provides a cross-platform way to achieve the copy, since cp
isn't a Windows command. To see all -E
options, run cmake -E help
.
You may consider using configure_file
configure_file("path-to-your-so-file.so" "new-path-to-your-so-file.so" COPYONLY)