muella91
muella91

Reputation: 329

Implementing a namespace without a class in C++

Should be an easy question, but I am struggling right now for a hour to wrap some helper functions in a namespace. Since I need need helper functions that do not have to be inside a class, I was recommend to wrap them into a namespace instead of making all of them static. See also here: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines

The problem is, whatever I do, I run into different errors. So whats the right way to write functions with a own namespace without creating a class? Lets take the following example. I tried already different variations of it.

My header file:

#ifndef BINARYCONVERTER_HPP
#define BINARYCONVERTER_HPP

#include <iostream>

namespace binary_converter {
    int myFunction(void);
}

#endif

And my source file:

#include "binary_converter.hpp"

int myFunction(void) {
    return true;
}

Thank you!

Upvotes: 1

Views: 1582

Answers (1)

NutCracker
NutCracker

Reputation: 12263

As said in the C++ docs:

Symbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken for identically-named symbols in other scopes.

Having that in mind function myFunction from your header file and funtion myFunction from your source file are not part of the same namespace. Function from the header file is part of the binary_converter namespace while function from the source file is part of global namespace.

Therefore, you need to wrap your function

int myFunction() {
    return 0;
}

from the source file into a binary_converter namespace like this:

namespace binary_converter {
    int myFunction() {
        return 0;
    }
}

or use scope operator to note that myFunction belongs to binary_converter namespace like this:

int binary_converter::myFunction() {
    return 0;
}

Upvotes: 6

Related Questions