I have a common header file being included in multiple cpp files I then compile to make the .so files of each cpp . But when I execute with the final executable, I am seeing that the common header file is being duplicated in the sense that all statements in that header file are being hit as many times as it has been included in the cpp.
How to avert it?
The common header file is:
// common.h
#ifndef _COMMON_H
#define _COMMON_H
#include<iostream>
int funcC();
const int x = funcC();
#endif // COMMON_H
The other files are:
// common.c
#include "common.h"
#include <iostream>
int funcC() {
std::cout<<"HI HI HI"<<std::endl;
return 2;
}
and
// main1.c
#include "common.h"
int main() {
return 0;
}
I was expecting it you print "HI Hi Hi" only once, but it's printing twice
This is a definition
This is the corresponding declaration
If you put a definition is a header file and include the header file multiple times, then you will get multiple definitions. Generally speaking that is an error, although there are exceptions. However it's fine to have multiple declarations (as long as they are all the same) so that is why generally speaking you only put declarations in header files.
There is an additional rule in C++ (but not C) that
constvariables automatically have local scope, (similar to declaring themstatic). That is why your code above does not result in a multiple definition error, although you do have multiple definitions ofxeach is local to the translation unit in which it appears. If you removed theconstyou would get a multiple definition error.Here then is a possible solution to your problem
The strange construct in common.cpp is the way you must define a non-locally scoped constant in C++.
constis by default local scope,externoverrides that, and then the initializer= funcC()turns what would otherwise be a declaration into a definition.