Reputation: 318
I'm reading Thinking in C++, 2nd Ed by Bruce Eckel, page 82, which reads, "You can declare a variable or a function in many different places, but there must be only one definition in C and C++ (this is sometimes called ODR: one-definition rule)."
What is a scenario that would benefit from declaring more than once? Would you ever need to do this or is it just for making the code more readable?
Thank you.
Upvotes: 2
Views: 2281
Reputation: 36487
You do so all the time, probably without noticing/thinking about it.
Whenever you include a header file you typically include declarations of stuff that's defined somewhere else.
Think about it in a different way: Everything you want to use somehow needs to be known to the compiler, which starts with a blank memory per translation unit. Declarations tell the compiler what some function looks like from the outside (the signature) or how big (in memory) some type is. Without this, it won't know how to call functions or how much memory to allocate/copy when working with stuff declared somewhere else.
Upvotes: 2
Reputation: 1327
Usually, you'll want to have only one place in a file where it's declared (such as in a .h
file.) This might turn into multiple places via #include
, which is why it may be defined in multiple places.
However, there are some (rare) scenarios where you might want to declare a function twice. For example, sometimes while debugging I might just insert:
void someFunction(int foobar);
Above the function I'm debugging, and then call someFunction
(even if it's in a different file, as long as it isn't static
.) This isn't necessarily a good practice, but perhaps I don't yet want to add a .h file and set it up in my Makefile/CMakeLists/etc. yet, e.g. because it will force more things to get recompiled.
There are some related scenarios, but I want to stress that this is considered bad practice. You wouldn't commit it this way; it might just be a quick hack.
Upvotes: 2
Reputation: 320441
"Declaring function in multiple places" is exactly what you do when you include a header file with function declaration into multiple translation units. That's basically an essential everyday practice in C++ (and C) programming.
Regardless of whether you use header files for that purpose, a function must be declared before its first use in each translation unit where it is used. Since a C++ program typically comprises multiple translation units, you have no choice but to declare the same function in multiple places.
You can also declare the same standalone (non-member) function multiple times in the same translation unit. There's no error in doing that. But most of the time this is indeed redundant.
Upvotes: 5
Reputation: 2776
You have to declare a function in each source file when the function is called. Or inside every calling function/method, if you do not like to declare it for the whole file.
This is the reason we put things like #include <iostream>
in each source file.
Upvotes: 1