Defining a global variable in the header?
Nov 16, 2015 at 7:15pm UTC
Hello, I have a variable named fSize in the header Structures.h and initialized it to 5:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
extern int fSize = 5;
#ifndef Ammount_H
#define Ammount_H
struct Workers
{
..code...
..code...
};
#endif
But when I go and implement this variable (through multiple files), I am given the error: fSize is ambiguous.
Example being implemented:
1 2 3 4 5 6 7 8 9 10
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
#include "Structures.h"
using namespace std;
Workers emp[fSize];
int c;
double Rate[fSize], Pay[fSize];
In the instance above, I am thrown acouple errors:
error C2872: 'fSize': ambiguous symbol
d:...Structures.h(8): note: could be 'int fSize'
How can I fix this problem?
Last edited on Nov 16, 2015 at 7:16pm UTC
Nov 16, 2015 at 8:10pm UTC
Use:
extern int fSize;
Nov 16, 2015 at 8:13pm UTC
Lines 8 and 10 in the second snippet are not valid C++, although some compilers allow this.
Compliant C++ requires that array sizes are known at compile time.
Nov 16, 2015 at 8:55pm UTC
have a variable named fSize in the header Structures.h
This variable should really be a const and it should not be initialized in the header. Something like:
1 2 3 4 5 6
// In the header file.
extern const int fSize;
// In one and only one of your source files.
const int fSize = 5;
All of the other source files will include the header to have access to this variable.
Topic archived. No new replies allowed.