Home > Software engineering >  Defining variables in a header file c
Defining variables in a header file c

Time:09-24

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;
}

CodePudding user response:

always defines variables that are global or const like

const int VARIABLE = 1;

then you can easily do

std::cout << VARIABLE << std::endl;

CodePudding user response:

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 
  • Related