Why is my code duplicating with shared objects?

81 Views Asked by At

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

1

There are 1 best solutions below

0
john On

This is a definition

int x;

This is the corresponding declaration

extern int x;

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 const variables automatically have local scope, (similar to declaring them static). That is why your code above does not result in a multiple definition error, although you do have multiple definitions of x each is local to the translation unit in which it appears. If you removed the const you would get a multiple definition error.

Here then is a possible solution to your problem

// common.h
extern const int x; // this is a declaration

// common.cpp
extern const int x = funcC(); // this is a definition

The strange construct in common.cpp is the way you must define a non-locally scoped constant in C++. const is by default local scope, extern overrides that, and then the initializer = funcC() turns what would otherwise be a declaration into a definition.