embed string via header that cannot be optimized away

后端 未结 3 1852
挽巷
挽巷 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 05:00

    You can embed assembly pseudo-ops in your header, and it should stay (although it's never used):

    asm(".ascii \"Frobnozzel v0.1; © 2019 ACME; GPLv3\"\n\t");
    

    Note that this is GCC/Clang-specific.

    An alternative for MSVC would be using #pragma comment or __asm db:

    __asm db "Frobnozzel v0.1; © 2019 ACME; GPLv3"
    #pragma comment(user, "Frobnozzel v0.1; © 2019 ACME; GPLv3")
    

    Here's an example:

    chronos@localhost ~/Downloads $ cat file.c 
    #include 
    
    #include "file.h"
    
    int main(void)
    {
            puts("The string is never used.");
    }
    chronos@localhost ~/Downloads $ cat file.h
    #ifndef FILE_H
    #define FILE_H 1
    
    #if defined(__GNUC__)
        asm(".ascii \"Frobnozzel v0.1; © 2019 ACME; GPLv3\"\n\t");
    #elif defined(_MSC_VER)
    # if defined(_WIN32)
        __asm db "Frobnozzel v0.1; © 2019 ACME; GPLv3"
    # elif defined(_WIN64)
    #  pragma comment(user, "Frobnozzel v0.1; © 2019 ACME; GPLv3")
    # endif
    #endif
    chronos@localhost ~/Downloads $ gcc file.c
    chronos@localhost ~/Downloads $ grep "Frobnozzel v0.1; © 2019 ACME; GPLv3" a.out
    Binary file a.out matches
    chronos@localhost ~/Downloads $ 
    

    Replace the gcc command with clang and the result is the same.

    For 64-bit Windows, this requires either replacing user with the deprecated exestr or creating a resource file that embeds the string in the executable file. As this is, the string will be removed when linking.

提交回复
热议问题