views:

59

answers:

1

I like to keep my Makefiles flexible and multifunctional. One of the tasks I usually add to make command is tar, for example the following instruction does the job:

tar:
    tar -cvf $(PROGNAME).tar $(SRCS) Makefile

My question is: How can CMake be used to generate personalized commands like tar?
I would like to see some code samples.
For the full functionality it would be useful to create project's components and be able to use them as parameters.
(Exempli gratia: archive only header files or some specific library).

Thanks in advance for your answers!

+1  A: 

The literal translation of your tar example would be:

ADD_CUSTOM_TARGET(tar
    tar -cvf ${CMAKE_CURRENT_BINARY_DIR}/${PROGNAME}.tar ${SRCS} Makefile
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})

This adds a new target "tar" that always executes the given command whenever it is requested as a command line target, i.e. whenever you run make tar it will create a new tar file. The WORKING_DIRECTORY argument will ensure that the source files are taken from the source directory, while CMAKE_CURRENT_BINARY_DIR ensures the output goes in the current build directory.

A slightly better iteration would be to replace tar with ${CMAKE_COMMAND} -E tar, as this doesn't depend on the command line tar program being available. So something like this would tar up all the header files when you run make tar:

SET(HEADER_FILES my.h another.h)
SET(PROGNAME myprog)
ADD_CUSTOM_TARGET(tar ${CMAKE_COMMAND} -E tar -czvf
    ${CMAKE_CURRENT_BINARY_DIR}/${PROGNAME}.tar.gz ${HEADER_FILES}
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})

An even better iteration would be to use the CPack features to create source or binary tar files, but that's quite a bit more work and may not be what you need anyway.

rq
Could not be explained better! Thank you!
Rizo
By the way, why would I want to backup `Makefile` when you use **CMake**? =)
Rizo
Why indeed! Maybe a wrapper Makefile that just had "mkdir build; cd build; cmake ..; $(MAKE) $(MAKECMDGOALS)"?
rq
That is a good idea! I'll use this wrapper!
Rizo