Declare value in c++ header

无人久伴 提交于 2019-12-13 07:15:40

问题


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


回答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?




回答2:


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.




回答3:


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"



回答4:


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;


来源:https://stackoverflow.com/questions/42310477/declare-value-in-c-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!