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 as following:


#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


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

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.



Leave a Reply

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

You are commenting using your 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