'How to store constants that can be read from all program, and also be used in defining functions?

I need to form a file named "constants.txt", and then use them when defining runge Funtion. Since the constants in the main function cannot be used outside the main function. How can I do about it?

Thanks!

float runge(float x, float y){
   return (-a*x+b*y+c/4.0+e*delta_t);} // where a,b,c,d,e,delta_t are from the file created
int main(){
    ofstream vOut("constants.txt", ios::out | ios::trunc);
    vOut.precision(5);
    vOut << "1.22" 
            << setw(5) <<"9.81"
            << setw(4) <<"0.0"<<endl;
    vOut << "3.0"  
            << setw(4) <<"1.0" 
            << setw(6) <<"0.01"<<endl;  
    vOut.close();
    
    const float a, b, c;
    const float d, e, delta_t;
    
    //read the file and set variables
    ifstream vMyFile("constants.txt");
    int i = 0;
    while (vMyFile >> a >> b >> c >> d >> e >> delta_t) {
    }
            vMyFile.close();



Solution 1:[1]

I think the simplest way is to define a header file named like constants.h, which contains like

#ifndef CONSTANTS_H
#define CONSTANTS_H

static const float a = 1;
static const float b = 2;
static const float c = 3;
static const float d = 4;
static const float e = 5;
static const float delta_t = 1E-5;

#endif

Any cpp file can include the header and there is no worry about redifining these variables.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Teddy van Jerry