Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> And, closer to something I've needed more than once, how do you give your program an int and string version number with only one thing to modify?

This is not very elegant, and you have to split your version number to major and minor part, but it does the job. Oh, yes, minor version must be between 0 and 99 (inclusive).

    #define VERSION_MAJOR 2
    #define VERSION_MINOR 9

    #define VERSION_INT (VERSION_MAJOR * 100 + VERSION_MINOR)
    #define STRINGIFY2(x) #x
    #define STRINGIFY(x) STRINGIFY2(x)
    #if VERSION_MINOR<10
    #define VERSION_STR STRINGIFY(VERSION_MAJOR) ".0" STRINGIFY(VERSION_MINOR)
    #else
    #define VERSION_STR STRINGIFY(VERSION_MAJOR) "." STRINGIFY(VERSION_MINOR)
    #endif



And if you don't need string constant, but just a string, then you can use the following (I'm not sure about portability though):

    #include <stdio.h>

    #define VERSION_INT 3209

    #if VERSION_INT < 100
    #error VERSION_INT less than 100
    #elif VERSION_INT < 1000
    #define VERSION_STR (char[]){VERSION_INT/100+'0','.',(VERSION_INT%100)/10+'0',(VERSION_INT%10)+'0',0
    #elif VERSION_INT < 10000
    #define VERSION_STR (char[]){VERSION_INT/1000+'0',(VERSION_INT%1000)/100+'0','.',(VERSION_INT%100)/1
    #endif

    int main(void)
    {
        printf("%d\n", VERSION_INT);
        printf("%s\n", VERSION_STR);
        return 0;
    }
Output:

    3209
    32.09


Good stuff. It's that second level of indirection that got me (your STRINGIFY2/STRINGIFY combo).




Consider applying for YC's Winter 2027 batch! Applications are open till November 2.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: