Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we declare and define functions separately in C++? [duplicate]

I have only just started learning C++, and I see that functions are usually declared and defined separately, for example:

// Declaration
void sayhi(std::string name);

// Definition
void sayhi(std::string name) {
  std::cout << "Hello, " << name;
}

I tried looking up but most of the questions were for the cases of Class, but my question is in more general terms, why do we separate them? What's the benefit?

like image 608
jshji Avatar asked Sep 12 '19 11:09

jshji


2 Answers

The same function can be used in different compilation units.

If it will be defined in a header and it is not an inline function or a function with the internal linkage then the One Definition Rule (ODR) will be broken provided that the header in included in several compilation units.

So usually such functions are declared in headers but defined in some modules. So using the header different compilation units will see the functions declarations and the functions will be defined only once.

If a program consists only from one compilation unit then there is no need to declare and define a function separatly because a function definition is at the same time its declaration.

like image 127
Vlad from Moscow Avatar answered Oct 21 '22 23:10

Vlad from Moscow


why do we separate them?

We don't.
As long as we can get away with it at least, as it violated DRY, introducing (only partially checked) repetition.

The problem is that C comes from a long line of single-pass compilers, and while C++ bolted lots of things on with templates and return-type-deduction, it didn't quite reverse that fact.

Thus, if you want to use a function before its definition, you have to provide a forward-declaration.

And if you want to use separate compilation for parts of your code, which is generally advisable for shorter compile-times and ability to use libraries (static or not) in other languages, without sources, or compiled with other options, you need some way to tell the compiler what will be there.

Header-files are collections of such forward-declarations, constant-declarations, inline-functions (inline-functions must be defined in every translation unit using them), type-definitions and the like.
Generally, implementation-files include the corresponding hesders first to verify they work and are self-contained.

Admittedly, the module system introduced with C++20 is a new twist and further reduces the need for forward-declarations.

like image 37
Deduplicator Avatar answered Oct 21 '22 23:10

Deduplicator