In my shared library I declared a function in a header file, and defined it in a.cpp source file. When linking an application with the library, the linker complains that the function is undefined and I don't know whether it's because of a missing namespace, different parameters, or something else.
If I could mark the function definition as "implementing a previous declaration", I would catch this declaration/definition difference during compilation, instead of later when I link an app with the library.
Is there something similar to the "override" keyword for class methods that would prevent me from defining a function without an existing matching declaration?
I could use -Wl,--no-undefined
but some libraries were created with the expectation that --no-undefined
will not be used.
Declare a function in a header file in a namespace, eg:
namespace N { void f(); }
Define the function in a .cc
file using a qualified function name :
void N::f() { /*...*/ }
This way if no declaration of f
in namespace N
matches the definition, a compiler error is issued.
The other answer by Maxim Egorushkin can be simplified as follows for some compilers:
Declare the function as normal in the header file:
void f();
Define the function using a qualified name with the unnamed namespace:
void ::f() { /* ... */ }
Obviously you can also place it in a namespace.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.