Search code examples
nsis

How can I extract a string from a C++ header file into an NSIS variable?


I have an application whose version number is specified in a C/C++ header file, version.h:

#ifndef VERSION_H
#define VERSION_H

#define APPLICATION_VERSION "1.2.3"

#endif

The version number is also specified in the NSIS script,

!ifndef VERSION
!define VERSION "1.2.3"
!endif

so that this string can be included in the name of the installer. Is there any way for the NSIS script to read this value directly out of version.h so that I only need to specify the version number in one place?


Solution

  • Use !searchparse, !searchreplace and !define /math to read/manipulate version numbers at compile time:

    !searchparse /file "c:\some\path\version.h" `#define APPLICATION_VERSION "` VERSION `"`
    

    This next example uses a temporary file so it can be tested without external dependencies:

    !tempfile testhdr
    !appendfile "${testhdr}" "#ifndef VERSION_H$\n"
    !appendfile "${testhdr}" "#define VERSION_H$\n"
    !appendfile "${testhdr}" '#define APPLICATION_VERSION "1.2.3"$\n'
    !appendfile "${testhdr}" "#endif$\n"
    
    !searchparse /file "${testhdr}" `#define APPLICATION_VERSION "` VER_MAJOR `.` VER_MINOR `.` VER_BUILD `"`
    !searchparse /file "${testhdr}" `#define APPLICATION_VERSION "` VER_STRING `"`
    
    !delfile "${testhdr}" ; Cleanup
    
    !warning "${VER_MAJOR}, ${VER_MINOR}, ${VER_BUILD}"
    !error "${VER_STRING}"
    

    It is also possible to write a header with a define that is both valid C and NSIS code:

    #define /*
    !define /**/ \
    FOO "Bar"