I'm using C++11's static_assert
to perform compile-time checks to prevent the use of insecure functions, and/or to provide feedback to the user when a new feature should be used and the relevant APIs are out of date (e.g. using std::strftime
, std::to_string
, etc.).
I want to force failure if any source code attempts to use outdated functions, but I need it to be totally cross-platform, and also bypass or workaround other 'helpers' such as Microsofts own deprecations.
I see I can use .sections when working with a gnu toolchain, which I can see the definition for in OpenBSD's cdefs.h (http://ninjalj.blogspot.co.uk/2011/11/your-own-linker-warnings-using-gnu.html) but I have nothing equivalent for Visual Studio.
For example, I can use the following code without a problem to prevent 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);
it may be unclean but works; but the trouble is when attempting to do the same with others that don't play as nicely, such as ctime
and 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'
Is there a way I can block specific functions (warning or compile failure), while providing a message for what to use in their place, without conflict from gcc/visual studio in a suitable way? The CRT macros in visual studio do not prevent the above error with the aforementioned defines.
I'm not convinced something like __declspec(deprecated) int strcpy(char*,char*);
(as noted here: C++ mark as deprecated) is going to always play ball, and is a lot more work & less descriptive than just setting a define for the function name.