0

I found the brilliant example how to add link variables with date and build number with Makefile:

OBJECTS=main.o
BUILD_NUMBER_LDFLAGS  = -Xlinker --defsym -Xlinker __BUILD_DATE=$$(date +'%Y%m%d')
BUILD_NUMBER_LDFLAGS += -Xlinker --defsym -Xlinker __BUILD_NUMBER=$$(cat buildnumber.num)

a.out: $(OBJECTS) buildnumber.num
    $(CC) $(LDFLAGS) $(BUILD_NUMBER_LDFLAGS) -o $@ $(OBJECTS)
buildnumber.num: $(OBJECTS)
    @if ! test -f buildnumber.num; then echo 0 > buildnumber.num; fi
    @echo $$(($$(cat buildnumber.num)+1)) > buildnumber.num

But all my attempts to repeat this in CMakeLists.txt fail...:-( For example:

ADD_CUSTOM_COMMAND(OUTPUT buildnumber.num 
    COMMAND @if ! test -f buildnumber.num; then echo 0 > buildnumber.num; fi
    COMMAND @echo $$(($$(cat buildnumber.num) + 1)) > buildnumber.num)

file (GLOB_RECURSE MAIN_SOURCES FOLLOW_SYMLINKS ./src/*.cpp)
add_custom_target(buildnumber.num DEPENDS ${MAIN_SOURCES})

I will be very thankful for the way how to implement this in cmake.

leonp
  • 487
  • 5
  • 22
  • Do you really want it added by the linker? Or is a single re-configured .cpp file with two #defines also OK (see http://stackoverflow.com/questions/7900661/how-to-read-a-cmake-variable-in-c-source-code/7900862#7900862)? – André Jul 13 '12 at 07:56
  • Yes, I do. Because linker vars will have always correct values and I want them to be updated on EACH compilation. Besides, using linker vars is much faster, as does not require recompilation...:-) – leonp Jul 13 '12 at 09:23
  • Take a look at http://stackoverflow.com/questions/1438535/how-to-run-a-command-at-compile-with-in-makefile-generated-by-cmake – André Jul 13 '12 at 09:58

1 Answers1

0

@Andre

Well, I got what I wanted, but in some clumsy way, as I am newbie in this stuff. Please, advice how to improve this (mainly how to avoid separate files). This is the CMakeLists.txt file:

include_directories(${CMAKE_CURRENT_BINARY_DIR})
set(CMAKE_EXE_LINKER_FLAGS " /Projects/Testnum/linker.scr")
add_custom_target(stam ALL COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/custom.cmake) 
add_executable(foo main.c ) 
add_dependencies(foo stam)

This is the additional custom.cmake file:

execute_process(COMMAND increment.scr )
execute_process(COMMAND cat buildnumber OUTPUT_VARIABLE _output OUTPUT_STRIP_TRAILING_WHITESPACE)
file(WRITE linker.scr "__BUILD_NUM = ${_output} ;")

This is the increment.csr file, which I did not succeed to insert into custom.cmake:

#!/bin/bash
var=`cat buildnumber`; sum=$((1 + $var )); echo $sum >buildnumber

And finally, this is the main.c:

#include <stdio.h>
extern char* __BUILD_NUM;
int main()
{
  printf("LINK_TIME_VALUE: %d\n", (int)&__BUILD_NUM);
  return 0;
}

Everything works, but seems to be too clumsy.

leonp
  • 487
  • 5
  • 22