-2

So I am really new to c++. I want to define a variable in a header file:

I have it like this in my .h file:

#pragma once
#define x = 0x1;

But when I do this in my .cpp file it doesn't work:

#include "x.h"

int main(){
std::cout << x << std::endl;
}
Johan Grip
  • 13
  • 4
  • 1
    `#define` is a text replacement tool (so you got `std::cout << = 0x1 << std::endl;`). `constexpr static auto x = 0x01;` would define a variable. – Jarod42 Sep 23 '21 at 11:16
  • 4
    whatever resource you are using to learn you should stop using it. `#define x = 0x1;` is not defining a variable. Seems like you could use a [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – 463035818_is_not_an_ai Sep 23 '21 at 11:16
  • Why do you think that it doesn't work? – eerorika Sep 23 '21 at 11:18
  • You can use `#define x 0x1` but that's a very bad idea. `#define` is used in special cases, for example different builds. At this level you should stay away from it. – Barmak Shemirani Sep 23 '21 at 11:23
  • Why do you think that its being in a header file is part of the problem? – molbdnilo Sep 23 '21 at 11:27
  • "doesn't work" needs elaboration. In what way? What is the error message? – L. Scott Johnson Sep 23 '21 at 11:33
  • You've defined a preprocessor macro. You did not define a variable, which would look like: `int x = 0x01;`. In general, headers are used for **declarations**, not for **definitions**. In this case, your header would **declare** `extern int x;` and elsewhere in some source file you'd **define** `int x = 0x01;`. – Eljay Sep 23 '21 at 11:59

2 Answers2

0

always defines variables that are global or const like

const int VARIABLE = 1;

then you can easily do

std::cout << VARIABLE  << std::endl;
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

They are not variables defined in the header file. they are macros.

Macros: Macros are a piece of code in a program that is given some name. Whenever this name is encountered by the compiler the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro. Lets understand the macro definition with the help of a program:

#include <iostream>

// macro definition
#define size 5
int main()
{
    for (int i = 0; i < size; i++) {
        std::cout << i << "\n";
    }

    return 0;
}

whenever you use size compiler replaces it with 5

#define x 0x1 
Saurabh Dhage
  • 1,478
  • 5
  • 17
  • 31