Search code examples
c++linkage

External Linkage in c++


I'm making a simple program dealing with poker hands and probabilities. I'm running test cases on various hands, and in my program I need a deck from which to draw my hand that is constant and global. My program has three main objects: Card, Hand, and Deck. I am trying to create a global deck but it seems no matter what I do I get an error saying globalDeck is undefined in hand.cpp. Here is the relevant code:

hand.cpp:

Hand::Hand(int &one, int &two, int &three, int &four, int &five)
{
    cardsinHand.push_back(globalDeck.copy(one));
    cardsinHand.push_back(globalDeck.copy(two));
    cardsinHand.push_back(globalDeck.copy(three));
    cardsinHand.push_back(globalDeck.copy(four));
    cardsinHand.push_back(globalDeck.copy(five));
}

and my cardgames.cpp file:

#include "stdafx.h"
#include<iostream>
#include "hand.h"
using namespace std;

Deck globalDeck;

void printresults(long successes, long trials)
......

Note: I have tried replacing Deck globalDeck with extern Deck globalDeck, extern const globalDeck, etc etc. Nothing seems to make it so that globalDeck is defined in hand.cpp. Also, the deck will stay constant throughout the program, so it could be declared as a global constant, or a global variable, whichever is easier. My error output is:

1>c:\users\\desktop\semesters past\winter 2013\computer programming\projects\cardgames\cardgames\hand.cpp(31): error C2065: 'globalDeck' : undeclared identifier
1>c:\users\\desktop\semesters past\winter 2013\computer programming\projects\cardgames\cardgames\hand.cpp(31): error C2228: left of '.copy' must have class/struct/union
1>          type is 'unknown-type'

Solution

  • Declare your global variable in one header file

    extern Deck globalDeck;
    

    and define it in cardgames.cpp

    Deck globalDeck;
    

    Explanation:The compiler has to see what globalDeck is before you can use it. And the compiler mostly processes each *.cpp individually, without looking at others. In header files you can say what things are in the program without giving the complete and unique definition.