1

I have been trying a few things out with 'extern' keyword. I wrote this basic function and I am not sure why my print function is not working. Kindly help me in understanding it.

test1.h #pragma once #include<iostream> using namespace std; extern int a; extern void print(); test1.cpp #include "test1.h" extern int a = 745; extern void print() { cout << "hi "<< a <<endl; } test2.cpp #include"test1.h" extern int a; extern void print(); int b = ++a; int main() { cout << "hello a is " << b << endl; void print(); return 0; } Actual output : hello a is 746 Expected output: hello a is 746 hi 746 
8
  • Have a read about storage class specifiers Commented May 21, 2019 at 4:39
  • From the link above: "The extern specifier is only allowed in the declarations of variables and functions (except class members or function parameters). It specifies external linkage, and does not technically affect storage duration, but it cannot be used in a definition of an automatic storage duration object, so all extern objects have static or thread durations. In addition, a variable declaration that uses extern and has no initializer is not a definition" Commented May 21, 2019 at 4:41
  • Possible duplicate of Access extern variable in C++ from another file Commented May 21, 2019 at 4:43
  • The issue has nothing to with extern– you would observe the same missing output if all the code were in the same file. Read about how to call functions in your favourite C++ book. Commented May 21, 2019 at 5:24
  • BTW: functions are extern by default in C++. Commented May 21, 2019 at 5:24

2 Answers 2

1

test1.cpp

#include "test1.h" int a = 745; //< don't need extern here void print() { //< or here cout << "hi "<< a <<endl; } 

test2.cpp

#include"test1.h" /* we don't need to redefine the externs here - that's what the header file is for... */ int b = ++a; int main() { cout << "hello a is " << b << endl; print(); //< don't redeclare the func, call it instead return 0; } 
Sign up to request clarification or add additional context in comments.

Comments

1

You need to use extern only when you are declaring variable/function, and define the variable in one of the cpp files,which include the header.

So, what you want to do is

test1.h

#pragma once #include<iostream> using namespace std; extern int a; extern void print(); 

test1.cpp

#include "test1.h" int a = 745; void print() { cout << "hi "<< a <<endl; } 

test2.cpp

#include"test1.h" int b = ++a; int main() { cout << "hello a is " << b << endl; print(); return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.