Search code examples
c++header-files

C++ not loading variables from header file


I'm trying to learn C++ (slowly) and am trying to get my head around header files. As far as I am aware, I can initialise my variables inside the header file, and then refer to them in my cpp file to use. I am trying to do this, but for some reason the cpp file is loading the header file successfully but not initialising any of the variables.

Have I misunderstood header files?

Header

#pragma once
#define _USE_MATH_DEFINES

#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <vector>




class learning_cpp
{
public:
    float SampleRate;

};

C++

#include "learning_cpp.h"

int main() {

    SampleRate = 1000;
};

Error: identifier "SampleRate" is undefined


Solution

  • All variables in C++ have their own visibility scope. Usually this scope between {}. Let's find that with example below:

    int main(void) {
        int my_int_var = 10;
        {
            int my_perfect_double_var = 10.0f;
        }
        /* the scope of my_perfect_double_var is limited to {}, so we can't use that variable here */
        /* but we can use my_int_var, because it have scope of the whole main function */
        my_int_var = 15; /* OK */
        my_perfect_double_var = 12.4f; /* ERROR here */
        
        return 0;
    }
    

    According to your code, your variables like SampleRate, Time, Frequency, etc. have scope inside the learning_cpp class. So you can use them ONLY inside an instance of this class
    To use them in code, you must first create an instance of the class, and then you can use the variables by accessing them from the instance:

    #include "learning_cpp.h"
    
    int main(void) {
        learning_cpp MyClass;
        MyClass.SampleRate = 15;
        MyClass.Frequency = 10;
        ...
    }