Arthur Tacca
Arthur Tacca

Reputation: 9998

Is it legal to declare but not define a function that is unused?

Let's say I have have the following files in C++:

// bar.hpp
int foo();
int bar();

// bar.cpp
#include "bar.hpp"
int bar() { return 3; }

// main.cpp
#include "bar.hpp"
int main() { return bar(); }

Note that foo() was declared (in both main.cpp and bar.cpp translation units) but never defined anywhere. On the other hand, it wasn't used anywhere either. Is this legal? I suspect it's fine in practice because neither compiled unit refers to the foo symbol so the linker will never try to find it. But I'm curious about whether the C++ standard guarantees that this is OK. (I'm not even sure that the standard talks about linking.)

Upvotes: 3

Views: 973

Answers (1)

Passer By
Passer By

Reputation: 21160

Yes it's legal. Functions and variables are required to be defined only when they are odr-used. odr-use is a precise way of saying use them, which for functions loosely means you call it or take its address.

To be a bit more precise, the function has to appear in a potentially-evaluated expression, which is everything except within

decltype
sizeof
typeid
noexcept

The standard indeed doesn't talk about linking, it instead only talks about translation units. Even though we usually just call an implementation a "compiler", we really mean the entire toolchain, including the linker. So even though the linker isn't explicitly mentioned, it is very much implied.

Upvotes: 8

Related Questions