Issues with placing a namespace in a seperate file

Im trying to organize some of my functions for a program that has become quite large. I want to use another file that holds a namespace 'Message' which wraps around my large functions that print text. I tried using just a cpp file and witing the namepace and functions in the same file, but the compiler gave me errors stating the functions had already been defined. I tried making a header file to hold the namepace declaration, then using a cpp file for the funciton definition, but the errors instead popped up saying the function has been defined mutiple times again. Here are the two files i attempted:

main.cpp(only the portion that gives me a problem)
1
2
3
4
5
6
7
8
9
int main()
{
    Map mObj(2);
    Message::SetMenu();
    Message::PrintOpening();
    do{LoopGame(mObj);}while(Restart());
    //BEYOND THIS POINT IN MAIN IS NEW CODE(UNFINISHED)
    std::cout << "\n\t\tThanks for playing!";
}



MessageNameSpace.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef MESSAGENAMESPACE_H_INCLUDED
#define MESSAGENAMESPACE_H_INCLUDED
namespace Message
{
    char MenuStruct[11][70];
    void SetMenu();
    void delay(unsigned long ms);
    void DisplayWinner(bool Winner);
    void PrintOpening();
}


#endif // MESSAGENAMESPACE_H_INCLUDED

MessageNameSpace.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include <windows.h>
#include "MessageNameSpace.h"

namespace Message
{
    void SetMenu(){ //read map in from "Map.txt" file
       //
    };

    void DisplayWinner(bool Winner)
    {
            //
    };

    void delay( unsigned long ms ) //sleep for _ miliseconds
        {
          //
    };

    void PrintOpening()
    {
            //
}


Error report:

obj\Debug\main.o||In function `main':|
F:\2DimMap(CONSOLE)\v1.08a\main.cpp|26|multiple definition of `Message::MenuStruct'|
obj\Debug\MessageNameSpace.o:F:\2DimMap(CONSOLE)\v1.08a\MessageNameSpace.cpp|10|first defined here|
||=== Build finished: 2 errors, 0 warnings ===|


Thanks if you can help at all!
Last edited on
Let begin with the fiirst error. Array char MenuStruct[11][70]; was defined twice. So you broke the one definition rule for objects.
Your array needs to be extern. Then in 1 implementation file and one only it needs to be defined.
updated post with a new error, thanks if you can help!
Last edited on
In MessageNameSpace.h
1
2
3
4
5
6
7
namespace Message
{
    //char MenuStruct[11][70]; // remove the definition
    extern char MenuStruct[][70]; // just declare the array
    enum { NUMMENUSTRUCTS = 11 } ;
    
// ... 



In MessageNameSpace.cpp
1
2
3
4
5
6
7
#include "MessageNameSpace.h"

namespace Message
{
    char MenuStruct[NUMMENUSTRUCTS][70]; // define the array

    // ... 


See: http://en.wikipedia.org/wiki/One_Definition_Rule
Last edited on
Thank you so much! it makes a LOT more sense now.
Topic archived. No new replies allowed.