I have this code, and I noticed that when I define my arithmethicStruct arithmethicArray[]
array without the static
attribute, I get a compile error of multiple definition. With the static
attribute, it compiles. Can I get an explanation of how this global static variables behave at compile time and why the error is suppressed, and the difference between a normal global one? I am a bit confused when using multiple files. Also a clarification of extern
would be helpful.
//main.cpp
#include "functionPointers.h"
#include <iostream>
int main() {
int a = getNumber();
char op = getOperatrion();
int b = getNumber();
arithmethicFunc func = getArithmeticFunct(op);
std::cout << a << " " << op << " " << b << " = " << func(a, b) << "\n";
return 0;
}
//functionPointers.h
int getNumber();
char getOperatrion();
typedef int (*arithmethicFunc)(int, int&);
int sum(int a, int&b);
int diff(int a, int&b);
int mult(int a, int&b);
int div(int a, int&b);
arithmethicFunc getArithmeticFunct(char op);
struct arithmethicStruct {
arithmethicFunc func;
char op;
};
//here is the question, with static it compiles
arithmethicStruct arithmethicArray[] {
{sum, '+'},
{diff, '-'},
{mult, '*'},
{div, '/'}
};
//functionpointers.cpp
#include "functionPointers.h"
#include <iostream>
int getNumber() {
int a;
std::cout << "Enter a number : ";
std::cin >> a;
return a;
}
char getOperatrion() {
char a;
std::cout << "Enter an operation (+, -, * , /) : ";
std::cin >> a;
return a;
}
int sum(int a, int&b) { return a+b; }
int diff(int a, int&b) { return a-b; }
int mult(int a, int&b) { return a*b; }
int div(int a, int&b) { return a/b; }
arithmethicFunc getArithmeticFunct(char op) {
switch (op) {
case '+': return sum;
case '-': return diff;
case '*': return mult;
case '/': return div;
}
}