0

我正在用不同的功能做 c++。我想把函数放在不同的源文件中。为此,我创建一个头文件:

函数.h

int X(int i, int k);

以及具有以下功能的文件:

函数.cpp

int X(int i, int k){    
return p + (i-1)*(n-1) + (k-1);
}

我有我的主要:

#include "subfunction.h"
int p, n, m, num_entries, NUMROWS;

int main (int argc, char **argv){

int project = 4;
int employee = 5; 
int time = 5; 
p=project;
n=employee;
m=time;

num_entries=-1;
int row=-1;
M[num_entries].col=X(i,k); 
}

我没有把所有的主要内容,只是有趣的部分。我的问题是 n,m 和 p 在我的 main 中是全局变量,但我也在我的函数中使用了它们。如果我在函数中声明它,则 main 不再起作用,如果我在 main 中声明它也是一样的。

我如何使用全局变量来做到这一点?谢谢

4

4 回答 4

3

In your function.cpp, declare the variables as

extern int p, n; // your function doesn't seem to need "m"

This instructs the compiler that the variables will be defined in some other module; you will have to include that other module together with your function code when linking, otherwise the linker will complain about unresolved externals.

However, using global variables like this is not a good way to write code. Refactor your code so that these become function arguments instead.

于 2013-05-17T09:35:53.380 回答
1

How I can do it using the global variable?

The best thing would be to pass the global variables to your functions explicitly. Global variables are a maintenance liability, your code will be easier to understand without them.

For example, you can do this:

int X(int i, int k, int n, int p);

If you need an ability to modify your globals, pass them by reference:

int X(int i, int k, int& n, int& p) {
    p += 24;
    n = 42;
    ...
}

If your globals are actually constants, declaring them const and put them in a header should fix the problem:

const int n = 42;

If for some reason you cannot do that, declare the globals extern int p etc. in the modules that must reference them.

于 2013-05-17T09:36:47.840 回答
0

In function.cpp, declare your global variables as

extern int p, n, m;

so the compiler knows it's defined elsewhere. I agree with the answer above that using global variables like this is considered bad form and should be refactored.

于 2013-05-17T09:35:39.230 回答
0

Declare p and n as extern:

extern int p;
extern int n;

int X(int i, int k){    
  return p + (i-1)*(n-1) + (k-1);
}
于 2013-05-17T09:36:37.163 回答