Yongy-vers
Yongy-vers

Reputation: 13

Failed to use namespace correctly in my .cpp file

I declare a namespace MYTIME in mytime.h file.

#include<ostream>
#ifndef _TIME_H
#define _TIME_H

namespace MYTIME{
        class time
        {
             ...
        };
}
#endif

And try to use it in my time.cpp file,

#include"mytime.h"
#include<iostream>

using namespace std;
using namespace MYTIME;

time::time()
{
        years = days = hours = minutes = 0;
        seconds = 0;
        months = JAN;
}

when I use g++ time.cpp to compile, errors are as follows

time.cpp:8:17: error: ‘MYTIME’ is not a namespace-name
 using namespace MYTIME;
                 ^~~~~~
time.cpp:8:23: error: expected namespace-name before ‘;’ token
 using namespace MYTIME;
                       ^
time.cpp:10:1: error: ‘time’ does not name a type
 time::time()

time.cpp:31:6: error: ‘time’ is not a class, namespace, or enumeration
 void time::addSec(long int s)
time.cpp: In function ‘void addSec(long int)’:
time.cpp:34:7: error: ‘seconds’ was not declared in this scope
  m = (seconds + s) / 60;
       ^~~~~~~
time.cpp:34:7: note: suggested alternative: ‘useconds_t’
  m = (seconds + s) / 60;
       ^~~~~~~
       useconds_t
   ... // many same errors

where am i going wrong? and how to fix it? Looking for help.

Upvotes: 0

Views: 385

Answers (1)

paddy
paddy

Reputation: 63451

Your header guard is using a name that is already defined. As a result, your namespace and class is never declared.

A simple test demonstrates the problem:

#include <iostream>

int main()
{
#ifdef _TIME_H
    std::cout << "Well, well, well...\n";
#endif
}

You would expect this program to have no output, but when compiled with g++ and run, this program outputs:

Well, well, well...

To solve this, you should use more uniquely named headers, and don't attempt to use naming conventions employed by the standard library. In particular, prefixing with an underscore is generally not a good idea.

If your compiler supports #pragma once you may wish to consider using that instead.

Upvotes: 1

Related Questions