0

is there any significance of making a variable and function inline and static inside a namespace. For example consider following 2 files:

consider first header file

// header1.h
#include <string>
#include <iostream>
namespace First
{
    static inline std::string s {"hi"};

    static inline void print(std::string str)
    {
        std::cout << str << std::end;
    }
}

and consider following second header file

// header2.h
#include <string>
#include <iostream>
namespace Second
{
    std::string s {"hi"};

    void print(std::string str)
    {
        std::cout << str << std::end;
    }
}

Does compiler see two codes differently or they introduce similar behavior ?

virus00x
  • 713
  • 5
  • 12
  • The one with the `static` has internal linkage while the other one without the static has external linkage. They're different from each other. – Jason Jun 21 '22 at 05:35
  • @AnoopRana Do not namespace variables and functions have internal linkage, like unnamed namespace ? – virus00x Jun 21 '22 at 05:39
  • No, see i have explained it in [C++ namespace and const variable](https://stackoverflow.com/questions/72364705/c-namespace-and-const-variable/72372140#72372140) in more detail. – Jason Jun 21 '22 at 05:40
  • See the comments in the code portion of my answer. In particular, `s` in `header1.h` have internal linkage and `s` in `header2.h` have external linkage. – Jason Jun 21 '22 at 05:47

1 Answers1

2

Do not namespace variables and functions have internal linkage, like unnamed namespace ?

No, your assumption that namespace(named namespaces) variables and functions by default have internal linkage is incorrect.

Does compiler sees two codes differently or they introduce similar behavior ?

The one with thestatic keyword have internal linkage while the other(in header2.h) have external linkage.

That is, the variable s in header1.h and header2.h are distinct from each other. Similarly, the functions are also different from each other.

header1.h

namespace First
{
    static inline std::string s {"hi"};       //s has internal linkage

    static inline void print(std::string str) //print has internal linkage
    {
        std::cout << str << std::end;
    }
}

header2.h

namespace Second
{
    std::string s {"hi"};        //s has external linkage

    void print(std::string str)  //print has external linkage
    {
        std::cout << str << std::end;
    }
}

Jason
  • 36,170
  • 5
  • 26
  • 60