In software development, maintaining a large codebase often involves updating APIs, replacing old functions, or removing unsafe code. However, simply deleting old code can break existing programs that still rely on it. This is where deprecating code comes in: you can mark functions, classes, variables, or other entities as obsolete while still keeping them available, giving developers a clear warning to migrate to newer alternatives. This tutorial demonstrates how to deprecate code in C++.
C++ provides a modern, standardized way to deprecate code using the [[deprecated]]
attribute (introduced in C++14).
Mark as deprecated
Here's a simple example of how to mark function as deprecated:
#include <iostream>
[[deprecated]] void test() {
std::cout << "Test function" << std::endl;
}
int main() {
test();
return 0;
}
The compiler will still allow the code to compile, but it will generate a warning. Compiler output example (GCC or Clang):
main.cpp: In function ‘int main()’:
main.cpp:8:9: warning: ‘void test()’ is deprecated [-Wdeprecated-declarations]
8 | test();
| ~~~~^~
main.cpp:3:21: note: declared here
3 | [[deprecated]] void test() {
| ^~~~
Mark as deprecated with message
You can also provide a message to guide developers to the preferred alternative function. This is very helpful in large projects to indicate which API should be used instead.
#include <iostream>
[[deprecated("Use test2 instead.")]] void test1() {
std::cout << "Test1 function" << std::endl;
}
void test2() {
std::cout << "Test2 function" << std::endl;
}
int main() {
test1();
return 0;
}
Sample compiler output:
main.cpp: In function ‘int main()’:
main.cpp:12:10: warning: ‘void test1()’ is deprecated: Use test2 instead. [-Wdeprecated-declarations]
12 | test1();
| ~~~~~^~
main.cpp:3:43: note: declared here
3 | [[deprecated("Use test2 instead.")]] void test1() {
| ^~~~~
Leave a Comment
Cancel reply