embed string via header that cannot be optimized away

后端 未结 3 1848
挽巷
挽巷 2021-02-14 04:40

While developing a header-only library, I\'d like to make sure that a given string is embedded in all binaries that use my header, even if the compiler is configured to optimize

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 04:51

    I don't know if there is any standard way of doing it, but depending on how your library works i might have a reasonable solution. Many libraries have init functions that are usually called only once or at least very rarely in the code. srand() is one example.

    You could require an init function for your library to work, and without specifying exactly it purpose, you could just say that the main function needs to have the line initlib(); before any library functions are used. Here is an example:

    l.h:

    // Macro disguised as a function
    #define initlib() init("Frobnozzel v0.1; © 2019 ACME; GPLv");  
    
    void init(const char *);
    void libfunc(void);
    

    l.c:

    #include "l.h"
    #include 
    #include 
    
    int initialized = 0;
    
    void init(const char *str) {
        if(strcmp(str, "Frobnozzel v0.1; © 2019 ACME; GPLv3") == 0)
            initialized = 1;
    }
    
    void libfunc(void) {
        if(!initialized)
            exit(EXIT_FAILURE);
        /* Do stuff */
    }
    

    Note: I know that you asked for header only, but the principle is the same. And afterall, converting a .h,.c pair to just a .h file is the simplest task in the world.

    If you use the library function libfunc before you have used the initialization macro initlib, the program will just exit. The same thing will happen if the copyright string is changed in the header file.

    Sure, it's not hard to get around this if you want, but it works.

    For testing, I used this code:

    int main()
    {
        initlib();
        libfunc();
        printf("Hello, World!\n");
    }
    

    I tried this by compiling l.c into a shared library. Then I compiled a simple main program with both clang and gcc using -O3. The binaries worked as they should and they contained the copyright string.

提交回复
热议问题