0

I am trying to compile a project in C++, VS 2012, and I am running into a LNK 2019 error. I have #ifndef macros on all my header files. I think it is getting confused about a file I included in a namespace that holds helper functions, as I am new to using namespaces and am possibly using them wrong. It looks like this:

Foo.h:

namespace fooSpace
{
    foo();
}

I include this in Foo.cpp:

using fooSpace;

foo ()
{
// definition of foo
}

I also include Foo.h in my Main.cpp, where I try to use the function by saying:

using fooSpace;

// Other stuff

fooSpace::foo();

Is there anything strikingly obvious as to why I would get the linker error? Or is it nothing necessarily here, and it's probably something else I've done?

Thanks very much for any response!

Lapys
  • 87
  • 2
  • 14
  • Post the complete error. – user657267 Oct 09 '14 at 02:04
  • I meant to upvote your comment, but I think it removed it. Please post the link you made again? I looked at the link at I followed Version 1 as recommended, and the code compiles just fine. This may seems stupid, but can you, or anyone else, explain why adding "fooSpace::" to the beginning of my function declaration works? I thought I didn't need it specifically because I had already said "using fooSpace;" at the top of the file. – Lapys Oct 09 '14 at 02:07
  • The code in the middle fragment implements `::foo`, not `fooSpace::foo` – Igor Tandetnik Oct 09 '14 at 02:07
  • Nevermind, here is the link: http://stackoverflow.com/questions/8681714/correct-way-to-define-c-namespace-methods-in-cpp-file – Lapys Oct 09 '14 at 02:07

2 Answers2

1

The definition must be either inside the namespace

namespace fooSpace {
    <return_type> foo() {
        // definition
    }
}

or qualified to indicate that it's the function in the namespace, not another function of the same name

<return_type> fooSpace::foo() {
    // definition
}

You are instead declaring and defining a new function, with the same name, in the global namespace, and leaving fooSpace::foo undefined.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Someone else technically answered first, but you set it as the answer and also explained precisely why it works in this fashion. Much appreciated, friend. – Lapys Oct 09 '14 at 02:09
1

In your code,

    using fooSpace; // this brings the declaration fooSpace::foo() into the current scope

    foo ()  // this is a new function in the current scope, which is ::foo()
    {
        // definition of foo
    }

So your function fooSpace::foo() has no definition yet.

CS Pei
  • 10,869
  • 1
  • 27
  • 46