如何在多个文件中使用变量

如何在多个文件中使用变量

本文介绍了如何在多个文件中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在标头中定义一个变量,并能够在多个文件中使用它.例如在某处定义了变量a并可以在p1.cpp和p2.cpp中使用/更改它

I want do define a variable in the header and be able to use it in multiple files.e.g. have variable a defined somewhere and be able to use/change it in both p1.cpp and p2.cpp

这里是一个示例,其中包含3个我想做的简单文件.

Here is an example with 3 simple files of what I'm trying to do.

// vars.hpp
#ifndef VARS_HPP
#define VARS_HPP

int a = 1;
float b = 2.2;
void double_vars();

#endif



// vars.cpp
#include "vars.hpp"
void double_vars () {
    a *= 2;
    b *= 2;
}

// vars_main.cpp
#include <cstdio>
#include "vars.hpp"
int main () {
    printf("a: %d; b: %f\n", a, b);
    double_vars();
    printf("a: %d; b: %f\n", a, b);
}

现在,使用以下命令编译以上内容:

now, compiling the above with:

g++ -Wall -W -g vars.cpp vars_main.cpp -o vars && ./vars

给我以下错误:

/tmp/ccTPXrSe.o:(.data+0x0): multiple definition of `a'
/tmp/ccnc1vof.o:(.data+0x0): first defined here
/tmp/ccTPXrSe.o:(.data+0x4): multiple definition of `b'
/tmp/ccnc1vof.o:(.data+0x4): first defined here

有人可以向我解释为什么会这样吗?据我所知,头文件中有防护措施,因此仅应包含一次,因此不应有多个声明

can someone explain to me why this happens? I have guards in the header file so as far as I understand it should only be included once so there should not be multiple declarations

推荐答案

首先,请不要这样做.全局可变状态通常是一件坏事.

First off, don't do this. Global mutable state is usually a bad thing.

问题在于,链接器完成将包含声明中的文件合并后,它已经两次见过,一次在main.cpp中,一次在vars_main.cpp中:

The problem is that once the linker finishes combining the files in your include statments, it has seen this twice, once in main.cpp and once in vars_main.cpp:

int a = 1;
float b = 2.2;

如果仅将其放在头文件中,则它将以多种翻译单位显示,对于包含头文件的每个cpp文件一次.编译器不可能知道您在说a和b.

If you only put this in the header file, it shows up in multiple translation units, once for each cpp file that includes your header. It's impossible for the compiler to know which a and b you're talking about.

解决此问题的方法是在标头中声明它们extern:

The way to fix this is to declare them extern in the header:

extern int a;
extern float b;

这告诉编译器a和b是在某个地方定义的,而不一定在代码的这一部分.

This tells the compiler that a and b are defined somewhere, not necessarily in this part of the code.

然后,在您的一个cpp文件中定义它们:

Then, in one of your cpp files you would define them:

int a = 1;
float b = 2.2;

这样,在ab的生存空间中就有一个定义明确的位置,编译器可以正确地连接点.

That way, there's one well-defined place for the storage for a and b to live, and the compiler can connect the dots properly.

这篇关于如何在多个文件中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 21:45