We have this header file: headerA.h
#pragma once
#include <iostream>
void HeaderADefinedFunction()
{
std::could << "HeaderDefinedFunction called!\n";
}
Then inside sourceB.cpp
#include "headerA.h"
void FunctionB()
{
HeaderADefinedFunction();
}
And inside sourceC.cpp
#include "headerA.h"
void FunctionC()
{
HeaderADefinedFunction();
}
What are the negative aspects of defining the function HeaderADefinedFunction() in the header file itself. Would that definition be in an optimal form for link-time symbol resolution of that particular function?
CodePudding user response:
The code as-shown should produce a link failure with multiply-defined HeaderADefinedFunction()
symbol.
The make the code actually valid, the function must be made inline
.
Is defining functions in header files malpractice?
Not at all. In fact, template
functions must be defined in the header1.
What are the negative aspects of defining the function HeaderADefinedFunction() in the header file itself.
One negative is that if you change the definition, you must rebuild every .cpp
which #include
s this header, increasing rebuild times.
Another is that your object files are larger.
Would that definition be in an optimal form for link-time symbol resolution of that particular function?
IF you define the function in the header (and make it inline), the compiler may choose to inline it into some (or all) of the call sites. No LTO required.
If you don't, the compiler will not be able to perform such inlining, unless you use LTO.
1 Unless you know all types the template
is instantiated with and provide explicit instantiation for all of them.