0

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

4 Answers 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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

1 Comment

Your link is not related to the usage of extern to declare variables that are defined in a different translation unit.
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);
}

1 Comment

I try to do this but my main still have error like p and n are undeclared :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.