Reputation: 61
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
Upvotes: 0
Views: 4877
Reputation: 817
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;
Upvotes: 0
Reputation: 561
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.
Upvotes: 1
Reputation: 937
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?
Upvotes: 1
Reputation: 11
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"
Upvotes: 0