简体   繁体   English

如何在 C++ 中正确使用全局变量?

[英]How do I properly use global variables with C++?

I'm trying to make a simple sorting algorithm visualizer in C++ using the SFML library as the graphics engine, but I'm having some issues using global variables.我正在尝试使用 SFML 库作为图形引擎在 C++ 中制作一个简单的排序算法可视化工具,但是我在使用全局变量时遇到了一些问题。

I keep getting an "[Variable] already defined in main.obj" error, but I don't know any other way to use the variable outside of main.我不断收到“[Variable] 已在 main.obj 中定义”错误,但我不知道在 main 之外使用该变量的任何其他方式。 If someone could help guide me to the right direction, that would be great.如果有人可以帮助引导我走向正确的方向,那就太好了。

Screenshot of the error output错误输出截图

main.cpp主文件

#include <iostream>
#include <SFML/Graphics.hpp>

sf::RenderWindow window(sf::VideoMode(800, 600), "Visualized Sorting Algorithm");
int unsortedArray[] = { 66, 83, 343, 111, 500, 182, 46, 370, 480, 527, 266, 167, 163, 551, 462, 101 };
int arrLen = std::end(unsortedArray) - std::begin(unsortedArray);
int height = 1;
float unit = 800 / arrLen;
bool done = false;

int main() {

    std::cout << arrLen << std::endl;

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            }
        }


    }

    return 0;
}

setup.cpp安装程序.cpp

#include "setup.h"
#include "bar.h"
#include "main.cpp"

void Setup::visualizeArray() {
    for (int i = 0; i < arrLen; i++) {
        Bar bar;
        bar.width = unit - 1;
        bar.length = -unsortedArray[i] * height;
        bar.x = i * unit;
        bar.y = 600;
        window.draw(bar.draw());
        window.display();
    }
}

bar.h酒吧.h

#pragma once
#include <SFML/Graphics.hpp>

class Bar {
public:
    float width;
    float length;
    float x;
    float y;
    float out;
    sf::Color white = sf::Color::White;
    sf::RectangleShape draw() {
        sf::RectangleShape bar(sf::Vector2f(width, length));
        bar.setPosition(sf::Vector2f(x, y));
        bar.setFillColor(white);
        return bar;
    }
};

I tried putting all the variables into a header file, but I still get the same error output.我尝试将所有变量放入头文件中,但仍然得到相同的错误输出。

Do not include main.cpp in setup.cpp.不要在 setup.cpp 中包含 main.cpp。 This is why it fails because the globals you define in main.cpp are now asso in setup.cpp.这就是它失败的原因,因为您在 main.cpp 中定义的全局变量现在也在 setup.cpp 中。

In setup.cpp you will need to refer to the globals as 'extern'在 setup.cpp 中,您需要将全局变量称为“extern”

eg例如

 extern int height;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM