设为首页 加入收藏

TOP

C++跨文件共享全局变量
2017-06-17 10:22:31 】 浏览:7160
Tags:文件 共享 全局 变量

1.问题描述

最近做项目的时候需要在多个cpp文件之间通过全局变量传递参数,因此写了一个小程序来尝试一下。

2.解决方法

一共用到5个文件:test1.h, test1.cpp test2.h test2.cpp main.cpp

test1.h

#ifndef TEST1_H
#define TEST1_H

#include 
  
   
#include 
   
     #include 
    
      extern int global_v; void modify_1(); void print_1(); #endif
    
   
  

test1.cpp

#include "test1.h"

using namespace std;

int global_v = 1;

void modify_1()
{
    global_v++;
    cout << "in test1, value increases to " << global_v << endl;
}

void print_1()
{
    cout << "in test1, value is " << global_v << endl;
}

test2.h

#ifndef TEST2_H
#define TEST2_H

#include "test1.h"

void modify_2();

void print_2();

#endif

test2.cpp

#include "test2.h"

using namespace std;


void modify_2()
{
    global_v++;
    cout << "in test2,value increases to " << global_v << endl; 
}

void print_2()
{
    cout << "in test2, value is " << global_v << endl;
}

main.cpp

#include "test1.h"
#include "test2.h"


using namespace std;

int main()
{
    cout << "in main function, initial global value is " << global_v << endl;


    modify_1();
    modify_2();

    print_1();
    print_2();

    return 0;
}

编译

g++ -o main test1.cpp test2.cpp main.cpp

运行得到结果如下图所示:
crZ喎?/kf/ware/vc/vc3NfZmlsZQ==" src="/uploadfile/Collfiles/20170616/20170616091828225.png" title="" />

可以看到,各个cpp里面的函数都能对全局变量进行修改,得到的全局变量的值都是最新的。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇string实现 下一篇cvReduce函数

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目