Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign array size with external global variable c++

I have the following simple example code:

1.

//param.h
extern int n;

2.

//param.cpp
int n =10;

3.

# include <iostream>
# include "param.h"
using namespace std;
int main()
{
    double Arr[n];
    return 0;
}

It does not compile since I cannot n is not defined.

why, what is the best way to resolve this issue while keeping the same structure?

like image 456
jarhead Avatar asked Aug 27 '26 11:08

jarhead


1 Answers

Two things: First of all you need to link with all object files generated from source. The second is that variable-length arrays are not a valid C++ construct.

To solve the first problem you need to make sure you compile both source files. Either together on the command line, or into separate object files that you link together to form the executable.

The second problem can be solved by using the const keyword in the declaration and definition to make it a compile-time constant.

like image 111
Some programmer dude Avatar answered Aug 29 '26 00:08

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!