在printf中使用#define?

Joh*_*ohn 2 c++ string c-preprocessor

我想要为应用程序ID使用某种常量(所以我可以在printf中使用它).

我有这个:

#define _APPID_ "Hello World!"
Run Code Online (Sandbox Code Playgroud)

然后是简单的printf,将其调用为%s(字符串).它说出来了:

simple.cpp:32: error: cannot convert ‘_IO_FILE*’ to ‘const char*’ for argument ‘1’ to ‘int printf(const char*, ...)’

我将使用什么来定义要在printf中使用的应用程序ID?我试过了:

static const char _APPID_[] = "Hello World"`
Run Code Online (Sandbox Code Playgroud)

但它没有用,我认为同样的错误.

Mar*_*off 6

我不确定我到底知道你尝试了什么...但这有效:

#include <stdio.h>

#define _APPID_ "Hello world"

int main()
{
    printf("The app id is " _APPID_ "\n");
    /* Output: The app id is Hello world */
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当两个常量字符串背靠背(即"hello " "world")时,编译器将它们视为单个连接常量字符串("hello world").

这意味着在尝试printf编译时常量字符串的情况下,您不需要使用printf("%s", _APPID_)(尽管这应该仍然有用).