Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring functions and variables multiple times in C++

In C++, declaring a variable multiple times shows an error during compilation. For example:

int x;
int x;

While declaring a function multiple times doesn't show any error during compilation. For example:

int add(int, int);
int add(int, int);

Why is this distinction in C++?

like image 233
Kushashwa Ravi Shrimali Avatar asked Dec 29 '16 05:12

Kushashwa Ravi Shrimali


1 Answers

Note that int x; is not (just) declaration, it's definition. So error arisen since ODR is violated, i.e. only one definition is allowed in one translation unit.

A declaration of variable could be written as:

// a declaration with an extern storage class specifier and without an initializer
extern int x;
extern int x;

In the meantime int add(int, int); is a declaration (of function) exactly. Multiple declarations in one translation unit are fine, ODR is not violated.

like image 129
songyuanyao Avatar answered Sep 20 '22 07:09

songyuanyao