Advertisement
Intermediate C++, Compilation & Linking

What is the difference between declaration and definition?

Short answer

A declaration introduces a name and its type (promising it exists somewhere); a definition also provides the implementation/storage. You can declare something many times but define it only once (per the ODR).

Save C++ mock interview
Advertisement
AModel answer
A declaration introduces a name and its type (promising it exists somewhere); a definition also provides the implementation/storage. You can declare something many times but define it only once (per the ODR). Header files typically contain declarations; source files contain definitions. Using an undeclared name is a compile error; a missing definition is a link error.
extern int x;      // declaration
int x = 5;         // definition
void f();          // declaration
void f(){}         // definition
Real-world example
A function declared in a header but never defined causes an 'undefined reference' at link time.
Likely follow-ups
  • How many times can you define something? | Where do declarations usually go?
Related topics