What is the difference between declaration and definition in C++?
Hi everyone! I just started learning C++ and got confused about the terms "declaration" and "definition". They both seem to be related to creating variables and functions, but I don't understand the fundamental difference.
For example, I write this code:
```cpp
int x; // Is this a declaration or a definition?
extern int y; // And this?
void foo(); // And this?
void foo() { } // And this?
```
When I write `int x;` inside a function, the compiler creates a variable and allocates memory for it. But when I write `extern int y;`, the program doesn't compile unless I add `int y;` somewhere else. Why is that? What's the logic here?
I also heard that a declaration can be repeated, but a definition cannot. But in practice, I get a "multiple definition" error if I write something twice.
No answers yet.
Log in to leave an answer
Blogs