.h 中的全局常量包含在多个 C++ 项目中

Global Constants in .h included in multiple c++ project

我想运行用c++做一个小的模拟。
为了保持一切美观和可读性,我将每个东西(比如所有 sdl 东西,所有主要的 sim 东西,......)分开到它自己的 .h 文件中。
我有一些我希望所有文件都知道的变量,但是当我将它们#include 在多个文件中时,g++ 编译器将其视为重新定义。
我理解他为什么这样做,但这仍然让我希望拥有一个文件,其中每个 运行 的所有重要变量和常量都已定义并为所有其他文件所知,以便在 运行宁我的模拟。
所以我的问题是:是否有一个很好的解决方法来实现这个或类似的东西?

在 header 中将它们标记为 extern 并有一个定义它们的翻译单元。

注意:如果没有 LTO(link 时间优化),这将严重降低您的模拟速度。

您可以将所有全局变量的声明放在 header 中,然后在源文件中定义它们,然后只需包含 header如下图:

header.h

#ifndef MYHEADER_H
#define MYHEADER_H


//declaration for all the global variables 
extern int i; 
extern double p;


#endif 

source.cpp

#include "header.h"
//definitions for all the globals declared inside header.h
int i = 0;
double p = 34;

main.cpp


#include <iostream>
#include "header.h" //include the header to use globals 
int main()
{
    std::cout << i <<std::endl;//prints 0
    std::cout<< p << std::endl;//prints 34
    return 0;
}

Working demo