0

Forgive me if this question doesnt make sense or if it may seem to easy but i am trying to understand how these header files

Is it possbile to declare inside of a header file variables with types like int and so on?

I have the following code and there is a problem with the lines where i declare window and the dimensions of the window.The compiler says there is a multiple definition of them being first defined in the main file where i simply have #include "core.h" and being defined again in the core.cpp where i again have a #include "core.h".

    #ifndef SFMLAPP_CORE_H
    #define SFMLAPP_CORE_H
    #include "SFML/Graphics.hpp"
    #include <iostream>
    
    sf::RenderWindow* window;///Window 
    float ScreenW,ScreenH;///Dimensions of the window
    
    struct position ///used in position handiling
     {
     float x=-1;
     float y=-1;
     };
    void printText(position pos,std::string Text,float size,float outlineSize);


    #endif //SFMLAPP_CORE_H
0x5453
  • 12,753
  • 1
  • 32
  • 61
  • 1
    It is worth to learn about [C++ compilation process](https://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work), this will answer your question and more. – Quimby Dec 08 '20 at 19:35
  • 1
    Please don't tag C++ stuff with C, see also the descriptions of those tags! As a new user, also take the [tour] and read [ask]. – Ulrich Eckhardt Dec 08 '20 at 19:36
  • 1
    It is possible but not recommended unless the variables are `const`. Global variables cause tons of headaches. – 0x5453 Dec 08 '20 at 19:36
  • If you are using C++17, you can declare them `inline`. – Paul Sanders Dec 08 '20 at 19:38
  • Prefer not to define variables in header files. Every source file that includes the header file will get an instance of that variable. Try implementing your code without using global variables. – Thomas Matthews Dec 08 '20 at 20:09

1 Answers1

5

You can not define variables in header files, however, you can declare them in a header file, then define them in a cpp file to make them accessible to other cpp files in your project.

core.h:

extern sf::RenderWindow* window;///Window 
extern float ScreenW,ScreenH;///Dimensions of the window

core.cpp

sf::RenderWindow* window;///Window 
float ScreenW,ScreenH;///Dimensions of the window

Everything else stays the same, but now you can access window and ScreenW, ScreenH from any file that includes core.h

Lev M.
  • 6,088
  • 1
  • 10
  • 23
  • 3
    You *can* define variables in header files (as in it's not explicitly disallowed by the language), you just *should not* do it because of the risk of multiple definition errors like this. Otherwise, spot on. – John Bode Dec 08 '20 at 19:45
  • And you must link the compiled cpp object when including the h file. – JHBonarius Dec 08 '20 at 20:47