-1

I have a variable defines in one .cpp file.

(file1.cpp)

int N;
....
N =3;

(directory/file2.cpp) ----> file2.cpp is in another directory.

extern int N;

cout << n << endl ;    -----> It is printing 0.

It should hv printed 3..right ? What is the mistake I am doing..Please let me know. Directory Structure is:

(main Directory)

file1.cpp   directory

(directory)

file2.cpp

Thanks, Avinash

Viktor Liehr
  • 508
  • 4
  • 14
  • 2
    Possible duplicate:http://stackoverflow.com/questions/12290451/access-extern-variable-in-c-from-another-file – m0bi5 Nov 09 '15 at 06:17
  • 2
    `n` is a different variable to `N`. C++ is csae sensitive. – M.M Nov 09 '15 at 06:46

2 Answers2

0

In one file this variable should be define as is:

  int N;

in others as extern (it is better to use header file to include such declaration), i.e.:

  extern int N;

The directory structure is not important, just cpp files must be compiled together to allow linker resolving connections.

VolAnd
  • 6,367
  • 3
  • 25
  • 43
0

To make it work you can use following approach:

Header file which provides the declarations so that other translation units can easily import it:

// dir1/file1.hpp
extern int N;

Implementation file with variable definition:

// dir1/file1.cpp
int N = 3;

Example client which uses the variable:

// main.cpp
#include "dir1/file1.hpp"

#include <iostream>

int main () {
    std::cout << N << std::endl;
    return 0;
}

Note that include guards are omitted in dir1/file1.hpp