0

If I define a namespace in multiple headers which contains declaration of function, class/struct definitions' interfaces then in the source files should I define those names inside the namespace itself or outside of it? e.g:

// file.h
namespace mylibNS{
    void func();
    struct Adder{
        int operator()(int const&, int const&) const;
    };
}

// file.cpp
#include "file.h"

void mylibNS::func(){}
int mylibNS::Adder::operator()(int const& x, int const& y) const{
    return + y;
}

Or should I do it this way:

// file.cpp
#include "file.h"

namespace myibNS{
    void func(){}
    int Adder::operator()(int const& x, int const& y) const{ // this doesn't compile
        return + y;
    }
}
  • What is the difference between the two versions and which one should I use? In fact I'm used to use the first one.

  • The second works for definition of function func but the compiler fails on defining the call operator of struct Adder: "Adder has not been declared".

Itachi Uchiwa
  • 1,659
  • 6
  • 20
  • 3
    Both are equivalent. Second doesn't compile because of a typo (`myibNS` instead of `mylibNS`). – Yksisarvinen Mar 22 '21 at 22:42
  • @Yksisarvinen: Oh my bad! I didn't notice that! thank you! – Itachi Uchiwa Mar 22 '21 at 22:44
  • @Yksisarvinen: Which is the better and the difference between them? – Itachi Uchiwa Mar 22 '21 at 22:46
  • 2
    @ItachiUchiwa • neither is better, and other than the syntax difference there is no other difference between them. Use whichever you (or your team) decide is the way you (or you all) like. – Eljay Mar 22 '21 at 22:47
  • 1
    @ItachiUchiwa • You don't have multiple *definitions* of `func()`, you have multiple *declarations* of `func()`, and that's okay. – Eljay Mar 22 '21 at 22:54
  • @Eljay: Thank you get it. – Itachi Uchiwa Mar 22 '21 at 22:54
  • Also, one fairly standard practice for header files is to use *header guards*, so the contents of the header file are only included in the translation unit once. `#ifndef GUARD_FILE_H` (some unique identifier that shouldn't collide with anything else) and `#define GUARD_FILE_H` at the very top, and `#endif` at the very end. – Eljay Mar 22 '21 at 22:59
  • @Eljay: What about using `#pragma once`? I am using GCC. – Itachi Uchiwa Mar 22 '21 at 23:00
  • 1
    Zack Weinberg, the person who invented `#pragma once` advises NOT to use it. q.v. https://stackoverflow.com/a/34884735/4641116 – Eljay Mar 22 '21 at 23:03
  • @Eljay: Thank you for the useful link. I've posted another topic on namespaces so please take a look. – Itachi Uchiwa Mar 22 '21 at 23:15

1 Answers1

0

Both ways are fine and equivalent. The first way is more explicit and easier to read, especially if there are more than one namespaces in the file. The second way is more convenient to write and is less cluttered as long as it's clear what's included in the namespace.

Woodford
  • 1,599
  • 7
  • 15