【问题标题】:How to share variable across files in different directory如何在不同目录中的文件之间共享变量
【发布时间】:2015-11-09 15:44:22
【问题描述】:

我在一个 .cpp 文件中定义了一个变量。

(file1.cpp)

int N;
....
N =3;

(directory/file2.cpp) ----> file2.cpp 在另一个目录中。

extern int N;

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

它应该打印 3..对吗?我在做什么错误..请告诉我。目录结构是:

(主目录)

file1.cpp   directory

(目录)

file2.cpp

谢谢, 阿维纳什

【问题讨论】:

标签: c++ extern


【解决方案1】:

在一个文件中,此变量应按原样定义:

  int N;

在其他为extern(最好使用头文件包含这样的声明),即:

  extern int N;

目录结构并不重要,只是cpp文件必须一起编译以允许链接器解析连接。

【讨论】:

    【解决方案2】:

    要使其正常工作,您可以使用以下方法:

    提供声明以便其他翻译单元可以轻松导入的头文件:

    // dir1/file1.hpp
    extern int N;
    

    带有变量定义的实现文件:

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

    使用变量的示例客户端:

    // main.cpp
    #include "dir1/file1.hpp"
    
    #include <iostream>
    
    int main () {
        std::cout << N << std::endl;
        return 0;
    }
    

    请注意,在 dir1/file1.hpp 中省略了包含保护

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 2021-07-10
      • 2017-03-27
      • 2016-05-31
      相关资源
      最近更新 更多