简体   繁体   中英

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.

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. 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

#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

#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. This is why it fails because the globals you define in main.cpp are now asso in setup.cpp.

In setup.cpp you will need to refer to the globals as 'extern'

eg

 extern int height;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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