Edward JR
Edward JR

Reputation: 1

C++ error "Variable or field declared void"

I have a problem with this error: "Variable or field declared void".

main.cpp

#include "header.h"

//Map per gestire il dizionario
std::map <std::string, Word> Dictionary;

int main()
{
    create_word();
    return 0;
}

header.h

#include <iostream> //Libreria I/O
#include <string> //Libreria per le String
#include <map> //Libreria per le Map
#include "class_word.h" //Libreria con classe Word
#include "function_dictionary.cpp" //Funzioni sul dizionario
#include "function_word.cpp" //Funzioni sulla classe Word

class_word.h

//Classe Word, rappresenta la parola del dizionario
class Word {
//Attributi privati della classe Word
private:
    std::string value; //Valore
    std::string desc; //Descrizione

//Metodi pubblici della classe Word
public:
    Word() {} //Costruttore
    Word(std::string val, std::string des) {value=val; desc=des;} //Costruttore con argomenti
    ~Word(){} //Distruttore
    std::string get_Value() {return value;} //Metodo per prendere la parola
    std::string get_Desc() {return desc;} //Metodo per prendere la descrizione
};

function_word.cpp

//Funzione per la creazione di una word
void create_word ()
{
    //Dichiarazione variabili
    std::string word, description;

    std::cout << "Parola: "; std::cin >> word;
    std::cout << "Descrizione: "; std::cin >> description;

    //Creazione Word
    Word temp(word, description);

    //Inserimento nel dizionario
    insert_dictionary(temp);
}

function_dictionary.cpp

//Funzione per inserire la parola nel dizionario
void insert_dictionary (Word temp)
{
    Dictionary.insert(make_pair(temp.get_Value(), temp));
}

At last file i have the error...How can i resolve? I think that was a bad include of file, but i can't resolve it... Help me pls...i am a newbie.

Upvotes: 0

Views: 6679

Answers (2)

TypeIA
TypeIA

Reputation: 17258

Dictionary is declared in main.cpp but nowhere else; you're then trying to use it in function_dictionary.cpp. It is undeclared there. You will need to put the declaration of Dictionary in one of the header files, using extern, which is included by both .cpp files.

This question fully explains how to share Dictionary between both source files, and shows how to use the extern keyword: How do I use extern to share variables between source files?

Also, it is generally bad practice to #include a .cpp file. This is almost certain to cause problems. The more common pattern is to declare everything in headers, then define things in .cpp files.

Upvotes: 1

Ferenc Deak
Ferenc Deak

Reputation: 35438

The problem is the order of inclusion:

firstly you include function_dictionary.cpp (via header.h) which uses the global symbol Dictionary which is strictly defined after that in the main.cpp

You break up too much these include things, it's not required.

Upvotes: 0

Related Questions