0

Well, i'm a newbie to C++ from Python and not familiar with declaring variable in header file. I am trying to create several .cpp file in which calculate some values from some the same constant value set. My code something like:

/Global_input.h/
extern int y = 1;
extern int x = 2;

/Properties_1.cpp/
//I wanna calculate z = x + y
include<Global_input.h>
int z;

/Properties_2.cpp/
//I wanna calculate g = x*y
include<Global_input.h>
int g;

I got stuck here, the way I search is create a new class or another .cpp file. Can I directly call x,y for such simple cases. Thanks in advance

An Nguyen
  • 67
  • 2
  • 10

4 Answers4

1

Use static const variable for this purpose:

static const int x = 1;

The const keyword here ensures that your code will not change x at any point (you stated that its value is supposed to be constant). I recommend reading the following SO thread to get an idea what the purpose of the static keyword is:

Variable declarations in header files - static or not?

Community
  • 1
  • 1
Nejc
  • 927
  • 6
  • 15
1

In addition to creating Global_input.h also create a Global_input.cpp file as follows -

/Global_input.h/
extern int y;
extern int x;

/Global_input.cpp/
#include "Global_input.h"

int y = 1;
int x = 2;

extern just declare the variable not define it. You must define it somewhere else.

army007
  • 551
  • 4
  • 20
  • `extern int y = 1;` defines `y` because it has an initializer. – Pete Becker Feb 18 '17 at 12:48
  • I guess that is not standard behavior (or at least good practice). Coz both `clang` and `gcc` give warning about it when the header is included in a single translation unit. And if the header is included in multiple translation unit (which is the case here) it complains about multiple references of `x` and `y`. – army007 Feb 18 '17 at 13:47
  • That **is** standard behavior. The reason that compilers complain about multiple definitions when you include that header in more than one translation unit is that each translation unit gets a definition. – Pete Becker Feb 18 '17 at 15:16
0

your my.h files should have this format:

//Put before anything else
#ifndef MY_H
#define MY_H

//code goes here

//at the end of your code
#endif

your my.cpp files should look like this:

//include header file you wish to use
#include "my.h"
0

You need to tell the compiler to only read once the header, e.g. like this:

/* Global_input.h */
#ifndef GLOBAL_INPUT_H
#define GLOBAL_INPUT_H
    static const int y = 1;
    static const int x = 2;
#endif

/* Properties_1.cpp */
//I wanna calculate z = x + y
#include<Global_input.h>
int z = x + y;

/* Properties_2.cpp */
//I wanna calculate g = x*y
#include<Global_input.h>
int g = x * y;
Ginés Hidalgo
  • 717
  • 9
  • 20