Paweł Audionysos
Paweł Audionysos

Reputation: 606

Define namespace scope function

I want to define public function in namespace scope (not in Class - this works) Basically I want use it like for example the:

std::chrono::milliseconds(16)

I've tried many setups but here is the recent one:

TimeX.h

#ifndef TIMEX_H
#define TIMEX_H

namespace timee{

    int now(int z);

}

#endif

TimeX.cpp

#include <chrono>
#include "TimeX.h"
using namespace timee;

int now(int z){return 4;}

Main.cpp

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

using namespace timee;

int main(int argc, char** argv){
    long c = now(2);
    std::cout << "c" << c <<std::endl;    
    return 0;
}

And this gives me following error:

Main.obj : error LNK2019: unresolved external symbol "int __cdecl timee::now(int)" (?now@timee@@YAHH@Z) referenced in function _SDL_main

What is the problem with this? It's confusing. Why linker tells me that this is referenced in _SDL_main? I use SDL library but what it has to do with my function?

Second problem related with this code.

And also one additional question (if it is not easy to answer I would start new topic). I'm using timee for namespace name because I've had an error telling that time name is used somewhere already Error C2757. I guess it is probably nested somewhere. How can I find out where it is used and is it possible to use the name anyway? I can't imagine how compiler have a problem in figuring out what I want to use.

Upvotes: 0

Views: 1079

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

You have to define the function like

int timee::now(int z){return 4;} 

Or you could write for example this way

#include <chrono>
#include "TimeX.h"

namespace timee
{
    int now(int z){return 4;}
}

Otherwise in the cpp module there is declared (and defined) another function with the same name in the global namespace

#include <chrono>
#include "TimeX.h"
using namespace timee;

int now(int z){return 4;}

That is these two definitions

int timee::now(int z){return 4;} 
int now(int z){return 4;}

define different functions. The first one declares (and defines) the function in the namespace timee while the second one declares (and defines) another function with the same name in the global namespace.

As for the name time then it is defined in the global namespace and corresponds to the C standard function time. For example the header <chrono> can in turn include the header <time.h> where the name time is declared.

Upvotes: 1

Related Questions