[CMake] Copy two files into one file

Michael Hertling mhertling at online.de
Sat Jul 10 14:49:10 EDT 2010

On 07/09/2010 06:39 PM, Bo Thorsen wrote:
> Den 09-07-2010 16:48, Michael Hertling skrev:
>> On 07/09/2010 03:48 PM, Bo Thorsen wrote:
>>> Hi all,
>>> Is there an elegant way of copying two files into one?
>>> Right now, I have this:
>>> ADD_CUSTOM_COMMAND(OUTPUT privilege_tables.sql
>>>                      COMMAND copy /b
>>>                        ${CMAKE_CURRENT_SOURCE_DIR}/system_tables.sql
>>>                        + ${CMAKE_CURRENT_SOURCE_DIR}/tables_fix.sql
>>>                        fix_privilege_tables.sql
>>>                      DEPENDS
>>>                      ${CMAKE_CURRENT_SOURCE_DIR}/system_tables.sql
>>>                      ${CMAKE_CURRENT_SOURCE_DIR}/tables_fix.sql)
>>> That's hardly elegant and it doesn't work :(
>>> The problem with this is that the Windows copy command wants \ instead of /.
>>> So, one of two fixes are possible for me: Either there is a much cleaner
>>> way to do this, or I have to replace / with \ in the path.
>>> If I have to do the replacement, is there a better way to do this than
>>> to use the STRING command with a char replace?
>> Look at the following CMakeLists.txt:
>> FILE(WRITE ${CMAKE_BINARY_DIR}/f1.c.in "void f1(void){}\n")
>> FILE(WRITE ${CMAKE_BINARY_DIR}/f2.c.in "void f2(void){}\n")
>> "int main(void){f1(); f2(); return 0;}\n"
>> )
>> FILE(WRITE ${CMAKE_BINARY_DIR}/concat.cmake "
>> FILE(READ \${SRC1} S1)
>> FILE(READ \${SRC2} S2)
>> FILE(WRITE \${DST} \${S1}\${S2})
>> ")
>>      OUTPUT f.c
>>                               -D SRC2=${CMAKE_BINARY_DIR}/f2.c.in
>>                               -D DST=${CMAKE_BINARY_DIR}/f.c
>>                               -P ${CMAKE_BINARY_DIR}/concat.cmake
>>      DEPENDS ${CMAKE_BINARY_DIR}/f1.c.in ${CMAKE_BINARY_DIR}/f2.c.in
>> )
>> ADD_EXECUTABLE(main main.c f.c)
> Does this also work with binary files? From the documentation on FILE, 
> this isn't really clear to me.

Regrettably, it doesn't. Binary files aren't read completely and without
changes to a string by FILE(READ ...). FILE(READ ... HEX), in contrast,
reads binary files correctly and stores them as a sequence of two-digit
hex numbers, but even if one manages to convert them to decimal numbers
- quite an effort in CMake - they cannot be written to a file since the
friend for this purpose, STRING(ASCII ...), fails at the zero character.

Thus, if you want to be plattform-independent the best thing you can do
is, IMO, to write a simple C/C++ program or the like which concats two
or more files, and deliver it for usage with ADD_CUSTOM_COMMAND() as a
part of your project. Perhaps, this issue would even be worth a feature
request, e.g. for a command "cmake -E concat" or FILE(WRITE ... HEX) or



More information about the CMake mailing list