Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

namespace functions not linking

I have a set up like this

file.h:

#pragma once
namespace a {
    int home(double a, double b, ...
    class b {
        int la();
    };
}

file.cpp

#include "file.h"    
using namespace a;

int home(double a, double b, ...) {
    //function stuff
}

int b::la() {
    home(1, 2, ...)
}

And b is instantiated and used in main like this:

#include "file.h"    
b instant;
instant.la()

But I have been getting this linker error everywhere where I am using the function home:

undefined reference to `a::home(double, double, ...)'
In function a::b::la()

I am pretty sure all of the CMakelists are correctly set up and everything is included.

But when I change the file.cpp to be in the namespace:

namespace a {
    all of the same stuff
}

and it works just fine?

Any ideas why this is happening?

Upvotes: 2

Views: 722

Answers (4)

Victor Zamanian
Victor Zamanian

Reputation: 3180

The definition of home needs to say a::home since that is the namespace it was declared within. Hence the undefined reference to "a::home".

Upvotes: 2

billz
billz

Reputation: 45410

In file.cpp wrap definitions inside namespace a, that will define them in namespace a and linker can find symbols.

namespace a{

int home(double a, double b, ...) {
    //function stuff
}

int b::la() {
    home(1, 2, ...)
}

} // namespace a

Node, using namespace a doesn't define your functions inside namespace a.

Have a look at google c++ coding style guide, it provides good c++ coding style.

Upvotes: 3

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361292

You need to define the function inside the namespace a because there is where it is declared:

namespace a
{
    int home(double a, double b, ...) {
      //function stuff
    }
}

Upvotes: 3

Yuushi
Yuushi

Reputation: 26040

Your problem is with using namespace a; up the top of your file.cpp. This is simply pulling in all the definitions from namespace a into your code. Thus, when you define int home(double, double, ...), you aren't providing an implementation for a::home, you're creating another function. You then have int a::home(double, double, ...) and int home(double, double, ...).

You either need int a::home(double, double, ...) or to wrap everything in your .cpp file that's under namespace a in namespace a { ... }.

Edit: Your confusion stems from what a using declaration does. It simply pulls everything in from the a namespace and allows you to use it unqualified. It does not allow you to omit the qualification in definitions.

Upvotes: 8

Related Questions