markOne
markOne

Reputation: 11

static and extern keywords LINK Error C++

I have wrote program to test static and extern keywords in C++.

source1.cpp

#include "Header.h"
using namespace std;

static int num;

int main(){
    num = 1;
    cout << num << endl;
    func();
} 

source2.cpp

#include "Header.h"

using namespace std;
extern int num;

void func(){
    num = 100;
    cout << num << endl;
}

Header.h

#ifndef HEADER_H
#define HEADER_H

#include <iostream>

void func();

#endif

When i compile this program it gives me a link error.

 error LNK2001, LNk1120 unresolved externals.

What is the reason to causes this Link error?

Upvotes: 0

Views: 175

Answers (1)

Deadlock
Deadlock

Reputation: 4519

This Link Error causes because of num variable declared as a static variable.

Even though the variable num is declared as an extern in the source2.cpp file, the linker won’t find it because it has been declared static in source1.cpp.

When you declared variable static, it is local to the file; it has file scope. That variable is unavailable outside of this file.

Upvotes: 2

Related Questions