Static keyword does not make function internal linkage?

In book "C Primer Plus" there is a paragraph about linkage of functions:
By default, C++ functions have external linkage, so they can be shared across files. But functions qualified with the keyword static have internal linkage and are confined to the defining file.

Then I try to check it by following codes

file ex1.h
1
2
3
4
5
#ifndef EX1_H
#define EX1_H
#include <iostream>
static int addadd(const int &x, const int &y){return x+y;} // static keyword make this function only internal linkage
#endif 

file run1.cc
1
2
3
4
5
6
#include <iostream>
#include "ex1.h"
int main(){
	int var1{2},var2{3};
	std::cout<<addadd(var1,var2)<<std::endl;
}


I anticipate an error displayed but it works properly. I wonder the static keyword in file ex1.h has to make function addadd internal linkage (can not be used in other files) and when I call it in file run1.cc, an error about not declaring must be. But it is not.

Would you explain it to me, please! Thanks.
The reason you're not seeing your expected error is because you have executable code inside a header file. Remember the #include copies the text from the header file into the source file. If addadd() was in a separate source file then you would not be able to use the function in another source file. Also if you had more than one source file #including that header you would probably have problems as well.

By the way instead of using the static keyword in C++ you can use an anonymous namespace instead.

file fun2.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
namespace
{
    int addadd(int x, int y)
    {
        return x + y;
    }
}

// Just to show that you can only use addadd() in this file.
int doaddition(int x, int y)
{
    return(addadd(x, y);
}

main.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int doaddition(int x, int y);

int main()
{
    cout << doaddition(1, 3) << endl;

    // Error.
    cout << addadd(1, 6) << endl;
    return(0);
}
Topic archived. No new replies allowed.