开发者

Using same variables in several functions

开发者 https://www.devze.com 2023-03-28 19:37 出处:网络
In my code, due to 开发者_运维知识库efficiency consideration, I place a long function in it\'s own file (let\'s name it a.cpp).I have also created a second file named b.cpp which holds another functio

In my code, due to 开发者_运维知识库efficiency consideration, I place a long function in it's own file (let's name it a.cpp). I have also created a second file named b.cpp which holds another function which uses the same variables names.

I have tried to create a header file for those variables but it didn't work. Is there a way to do that (apart from placing the functions in the same file)?

A simple example:

a.cpp

double s;

void a(){
  s = 1.0;
  printf("%f\n",s);
}

b.cpp

double s;

void b(){
  s = 2.0;
  printf("%f\n",s);
}

Note Each of those file is, in effect a c but the whole program is c++.


Write extern double s; in both (or in a header). This is a declaration without being a definition.

Then write double s; in just one .cpp file — this is where the double object will physically "live".

More here.


Put double s; in a.cpp. Write extern s; in a.h.

Also good programming practice is a function should fit onto a screen/one side of a5.


Put double s in a header file.

At the top of each .cpp file do:

#include "filename.h"

to introduce the variable into the cpp file for use. It would be good to define it as static as well... but we don't go into that.

PS: You shouldn't use globals like this if avoidable. It's not good OO design.

0

精彩评论

暂无评论...
验证码 换一张
取 消