I have below four files,
//struct.h
#pragma once
namespace coffee {
class MD2 {};
class Recorder{};
class Book{};
}
//setup.h
#pragma once
#include "struct.h"
using namespace coffee;
void wire(MD2 md2, Book book){}
//strategy.h
#pragma once
#include "struct.h"
#include "setup.h"
namespace strategy {
using namespace coffee;
int wire(MD2 md2, Recorder recorder) {}
int setup2(MD2 md2, Recorder recorder, Book book) {
wire(md2, recorder);
wire(md2, book); //<--compiler cant find this
}
}
//main.cpp
#include <iostream>
#include "strategy.h"
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
My problem is before using namespace coffee, the program compiles fine, but after adding namespace coffee, the compiler cant find wire(md2, book).
May I know why?
As Joel pointed out in the comment to your post, you should not be using namespace in C++ headers.
To save any developer that might be working with you or with your code some headaches, I would also refrain from using
using namespacealtogether, as it will reduce readability of the code for any larger codebase.Even for your small code example, I had to look twice to see that
Recorderwas part ofcoffee. Simple writing outcoffee::Recorderetc., makes for more readable code and avoids annoying mistakes down the road.