Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 854
Fantastic Mr Fox Avatar asked Aug 01 '26 05:08

Fantastic Mr Fox


2 Answers

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.

like image 167
Yuushi Avatar answered Aug 03 '26 20:08

Yuushi


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
    }
}
like image 20
Nawaz Avatar answered Aug 03 '26 21:08

Nawaz