从C ++调用NSLog:“格式字符串不是字符串字面量(可能不安全)”。 [英] Calling NSLog from C++: "Format string is not a string literal (potentially insecure)"
问题描述
当我从C ++调用NSLog时,Xcode抱怨传递给NSLog的格式字符串不是文字字符串。这是一行代码触发警告:
When I call NSLog from C++, Xcode complains that the format string passed to NSLog is not a literal string. Here's a line of code that triggers the warning:
NSLog(CFSTR("Leaking?"));
我不知道有任何方法来编写一个字面量的NSString在C + +,看到相关的警告,我可以在项目设置中关闭。有没有办法从C ++调用NSLog不触发此消息?我使用Xcode 4.2.1。
I'm not aware of any way to code a literal NSString in C++, and I don't see a relevant warning I can turn off in the project settings. Is there a way to call NSLog from C++ without triggering this message? I'm using Xcode 4.2.1.
编辑:这真的是C ++代码。我通常避免使用Objective-C ++,坚持Objective-C或普通的老C ++,因为没有关于什么在Objective-C + +什么工作的官方文档和什么不。我只发现了模糊的警告,(例如)STL的某些部分可能有问题。我使用模板,STL和C ++的其他高级功能,所以我想要安全。
This really is C++ code. I usually avoid Objective-C++, sticking to either Objective-C or plain old C++, because there's no official documentation about what works in Objective-C++ and what doesn't. I've only found vague warnings that (for example) there may be issues with some parts of the STL. I use templates, the STL, and other "advanced" features of C++, so I want to play it safe.
编辑#2,解决方案: clang支持比实际记录的更多的警告标志。 (应该从Xcode提供给我的警告长列表中显而易见。)我尝试了-Wno格式非线性a gcc,现在Xcode是快乐的。
Edit #2, the solution: I just figured out clang supports a lot more warning flags than are actually documented. (It should have been obvious from the long list of warnings that Xcode offered me.) I tried -Wno-format-nonliteral a la gcc, and now Xcode is happy.
推荐答案
所有你需要做的是写 @this
创建一个文本NSString对象。
All you have to do is write @"this"
to create a literal NSString object.
那么用 NSLog(@Leaking?);
应该很好。
您可能需要使用扩展名 .mm
重命名文件,以确保它已编译作为Objective-C ++(Objective-C和C ++的突变爱情孩子)。如果你不想这样做,你可以在一个小的mm文件中调用NSLog,然后从你的C ++代码调用该函数。它看起来像这样:
You might have to rename your file with the extension .mm
to make sure it is compiled as Objective-C++ (the mutant love-child of Objective-C and C++). If you don't want to do that, you could make a wrapper function in a tiny mm file that calls NSLog, and then call that function from your C++ code. It would look like this:
void MyNSLog(const char *message)
{
NSLog(@"%s", message);
}
请注意,编译器给你的悲伤的原因是,不可变的字符串文字(其中内容在编译时是已知的)是一种安全风险。否则,可以将格式字符串更改为包含不存在的参数的格式说明符(例如,%d
)。如果发生这种情况,NSLog将只是从堆栈获取随机指针,可能会发生不良。 (有关详情,请参见此问题。 )
Note that the reason the compiler is giving you grief is that using anything but an immutable string literal (where the contents are known at compile time) is a security risk. Otherwise, the format string could be changed to include format specifiers (e.g., %d
) for parameters that aren't there. If that happened, NSLog would just get random pointers from the stack and something bad could happen. (See this question for more info.)
这篇关于从C ++调用NSLog:“格式字符串不是字符串字面量(可能不安全)”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!