[英]How do I properly use global variables with C++?
我正在尝试使用 SFML 库作为图形引擎在 C++ 中制作一个简单的排序算法可视化工具,但是我在使用全局变量时遇到了一些问题。
我不断收到“[Variable] 已在 main.obj 中定义”错误,但我不知道在 main 之外使用该变量的任何其他方式。 如果有人可以帮助引导我走向正确的方向,那就太好了。
主文件
#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;
}
安装程序.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();
}
}
酒吧.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;
}
};
我尝试将所有变量放入头文件中,但仍然得到相同的错误输出。
不要在 setup.cpp 中包含 main.cpp。 这就是它失败的原因,因为您在 main.cpp 中定义的全局变量现在也在 setup.cpp 中。
在 setup.cpp 中,您需要将全局变量称为“extern”
例如
extern int height;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.