Marco A.
Marco A.

Reputation: 43662

Confusion with functions with static linkage

I'm unsure of the following code:

.lib project

Unit.h

namespace mynamespace {

    static void myFunction()
    {
      printf("hello world");
    }

    void myFunction2();
 }

Unit.cpp

#include "Unit.h"

void myFunction2() { printf("hello world"); }

.exe project

mainapp.cpp

   #include "Unit.h"

   int main()
   {
      mynamespace::myFunction();
      mynamespace::myFunction2();
      return 0;

   }

1) Why am I getting "unresolved external symbol" for myFunction2() ? I'm including the header and the symbol is in another translation unit, what's wrong?

2) static should mean "with internal linkage", does this mean that both mainapp.cpp and unit.cpp will have their "copy" of myFunction ?

Upvotes: 2

Views: 59

Answers (2)

Alexes
Alexes

Reputation: 230

... implement the function in the namespace ...

Unit.cpp

namespace mynamespace {
  void myFunction2() { printf("hello world"); }
}

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234635

You need to implement the function in the namespace:

void mynamespace::myFunction2() { printf("hello world"); }

Currently, in Unit.cpp, you're defining a different function; a function with name myFunction2 in the global namespace.

Upvotes: 8

Related Questions