patraulea
patraulea

Reputation: 916

How to ensure a C++ function is declared before being defined (like the override keyword)?

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.

Upvotes: 0

Views: 147

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136475

Declare a function in a header file in a namespace, e.g.:

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.

Upvotes: 6

Hans Olsson
Hans Olsson

Reputation: 12517

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.

Upvotes: 0

Related Questions