usertfwr
usertfwr

Reputation: 309

C++ function in different source files with global variable

I'm doing c++ with different function. I want to put the function in different source file. To do I create a header file:

function.h

int X(int i, int k);

and the file with the function:

function.cpp

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

and I have my main :

#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); 
}

I didn't put all my main, just the interesting part. My problem is that n,m and p are global variable in my main but I also used them in my function. If I declare it in the function, the main doesn't work anymore and same if I declare in the main.

How I can do it using the global variable? Thanks

Upvotes: 0

Views: 214

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

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.

Upvotes: 1

Oswald
Oswald

Reputation: 31657

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);
}

Upvotes: 0

Jon
Jon

Reputation: 437386

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.

Upvotes: 3

Elle
Elle

Reputation: 3775

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.

Upvotes: 0

Related Questions