//.h文件
#pragma once
#include <iostream>
using namespace std;
namespace test1 {
int make;
void func();
}
namespace test2 {
void func();
}
//test.cpp文件
#include <iostream>
#include "test.h"
void test1::func()
{
std::cout << "func" << std::endl;
}
命名空间.cpp文件
#include<iostream>
#include"test.h"
using namespace std;
//2.
namespace A {
int a;
namespace B {
int b;
}
}
//3.
namespace A {
int c;
}
//5.
void test()
{
namespace C = A;
}
int a;
int main()
{
int a;
test1::func(); //6.
return 0;
}
若我要在命名空间.cpp文件中使用.h文件中的make时,错误提示是test1命名空间中不包含make,但是我在定义make后编译时,也没有提示重定义的问题?
一般来说不能在头文件里定义变量,因为头文件很可能被不同的cpp文件包含多次,这样就导致了该变量被多次定义,违背ODR (One Definition Rule)。
但你可以在头文件里声明该变量,即在前面加上extern
,然后在其中一个cpp文件里定义该变量,这样这个变量只有一个定义,符合ODR。
https://en.cppreference.com/w/cpp/language/definition
因为不在一个命名空间下呀
不在一个命名空间,就不能访问,当然不重名了
你要访问其他命名空间,那需要include进来