Linkage of C++ functions

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.

To understand it, I tried to write 2 files, one is ex1.h and another is run1.cc as following:

ex1.h

#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

run1.cc

 

#include <iostream>
#include "ex1.h"
int main(){
	int var1{2},var2{3};
	std::cout<<addadd(var1,var2)<<std::endl;
}

I expected an error but there was not any one. Then I asked on a C++ forum and get the following explanation:

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.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s