Can a compilation error be forced if a string argument is not a string literal?

前端 未结 7 1912
说谎
说谎 2020-12-17 20:24

Let\'s say I have these two overloads:

void Log(const wchar_t* message)
{
    // Do something
}

void Log(const std::wstring& message)
{
    // Do someth         


        
相关标签:
7条回答
  • 2020-12-17 20:56

    Here's a quick example I just whipped up using the printf hack I suggested in the comments above:

    #include <cstdio>
    
    #define LOG_MACRO(x) do { if (0) printf(x); Log(x); } while (0)
    
    void Log(const char *message)
    {
        // do something
    }
    
    void function(void)
    {
        const char *s = "foo";
        LOG_MACRO(s);
        LOG_MACRO("bar");
    }
    

    Output from compiling this one with Clang appears to be exactly what you're looking for:

    $ clang++ -c -o example.o example.cpp
    example.cpp:13:15: warning: format string is not a string literal
          (potentially insecure) [-Wformat-security]
        LOG_MACRO(s);
                  ^
    example.cpp:3:41: note: expanded from macro 'LOG_MACRO'
    #define LOG_MACRO(x) do { if (0) printf(x); Log(x); } while (0)
                                            ^
    1 warning generated.
    

    I did have to switch to printf rather than wprintf, since the latter appears not to generate the warning - I guess that's probably a Clang bug, though.

    GCC's output is similar:

    $ g++ -c -o example.o example.cpp
    example.cpp: In function ‘void function()’:
    example.cpp:13: warning: format not a string literal and no format arguments
    example.cpp:13: warning: format not a string literal and no format arguments
    

    Edit: You can see the Clang bug here. I just added a comment about -Wformat-security.

    0 讨论(0)
提交回复
热议问题