在 printf 中使用 #define 吗?
我想使用某种常量作为应用程序 ID(这样我就可以在 printf 中使用它)。
我有这个:
#define _APPID_ "Hello World!"
然后是简单的 printf,将其调用到 %s (字符串)中。它输出了:
simple.cpp:32: error:无法将参数'1'转换为'_IO_FILE*'到'const char*'到'int printf(const char*, ...)'
我将使用什么来定义要在 printf 中使用的应用程序 ID?我尝试过:
static const char _APPID_[] = "Hello World"`
但它不起作用,我认为同样的错误。
I was wanting to use a constant of some kind for the application ID (so I can use it in printf).
I had this:
#define _APPID_ "Hello World!"
And then the simple printf, calling it into %s (string). It put this out:
simple.cpp:32: error: cannot convert ‘_IO_FILE*’ to ‘const char*’ for argument ‘1’ to ‘int printf(const char*, ...)’
What would I use to define the application ID to use in printf? I tried:
static const char _APPID_[] = "Hello World"`
but it didn't work, same error I think.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
_APPID_
是为实现保留的名称。它匹配模式^_[AZ].*
将其重命名为
APP_ID
。_APPID_
is a name that's reserved for the implementation. It matches the pattern^_[A-Z].*
Rename it to e.g.
APP_ID
.我不确定我是否完全理解您尝试过的内容...但这有效:
当背靠背呈现两个常量字符串(即
"hello " "world"
)时,编译器将它们视为单个连接常量字符串(“hello world”
)。这意味着,在尝试
printf
编译时常量字符串的情况下,您不需要使用printf("%s", _APPID_)
(尽管这应该仍然有效)。I'm not sure I understand exactly what you tried... but this works:
When presented with two constant strings back to back (i.e.
"hello " "world"
), the compiler treats them as a single concatenated constant string ("hello world"
).That means that in the case of trying to
printf
a compile-time constant string, you don't need to useprintf("%s", _APPID_)
(although that should still work).根据错误消息,问题很可能不是由字符串常量引起的,而是由给
printf()
提供的参数不正确引起的。如果您想打印到文件,您应该使用
fprintf()
,而不是printf()
。如果要打印到屏幕,请使用printf()
,但不要将文件句柄作为其第一个参数。According to the error message, the problem is most likely not caused by the string constant, but by incorrect parameters given to
printf()
.If you want to print to a file, you should use
fprintf()
, notprintf()
. If you want to print to the screen, useprintf()
, but don't give a file handle as its first parameter.在 source.h 中
在您的程序中:
这样做的原因是有一个标准包含文件 - source.h。头文件内的 __FILE__ 返回头文件的名称,因此 APP_ID 定义仅限于 C 文件中。
如果不定义 APP_ID,代码将无法编译。
In source.h
In your program:
the reason for this is to have a stadnard include file - source.h.
__FILE__
inside a header file returns the name of the header file, so the APP_ID definition is constrained to live in the C file.If you don't define APP_ID the code won't compile.