ZXc*_*bnM 5 c++ gcc cross-platform visual-studio c++11
我正在使用C++ 11 static_assert来执行编译时检查以防止使用不安全的函数,和/或在应该使用新功能并且相关的API已过时时向用户提供反馈(例如,使用std::strftime,std::to_string等).
我想强制失败,如果任何源代码试图使用过时的功能,但我需要它完全跨平台,并绕过或解决其他'帮助',如微软自己的折旧.
我在使用gnu工具链时可以使用.sections,我可以在OpenBSD的cdefs.h中看到这个定义(http://ninjalj.blogspot.co.uk/2011/11/your-own-linker-warnings -using-gnu.html)但我没有与Visual Studio等效的东西.
例如,我可以使用以下代码没有问题来防止strcpy/ strcat:
# define COMPILE_TIME_CHECK(expression, message) static_assert(expression, message)
# define GUARANTEE_FAILURE (0 == 1)
# define DISABLED_FUNCTIONS_MESSAGE_CSTRING "strcpy, strcat must be replaced with strlcpy and strlcat, respectively"
# define strcat COMPILE_TIME_CHECK(GUARANTEE_FAILURE, DISABLED_FUNCTIONS_MESSAGE_CSTRING);
Run Code Online (Sandbox Code Playgroud)
它可能是不洁净但有效; 但问题是当试图对那些不能很好玩的人做同样的事情,比如ctime和localtime:
_CRT_INSECURE_DEPRECATE(localtime_s) static __inline struct tm * __CRTDECL localtime(const time_t * _Time)
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\time.inl(86): error C2059: syntax error : 'static_assert'
Run Code Online (Sandbox Code Playgroud)
有没有办法可以阻止特定的功能(警告或编译失败),同时提供一个消息,说明在他们的位置使用什么,而不会以合适的方式与gcc/visual studio发生冲突?Visual Studio中的CRT宏不会阻止上述定义的上述错误.
我不相信__declspec(deprecated) int strcpy(char*,char*);(如此处所述:C++标记已被弃用)将始终发挥作用,并且比仅仅为函数名称设置定义更多的工作和更少的描述.