Skip to content

Instantly share code, notes, and snippets.

@zz-jason
Last active March 22, 2017 14:52
Show Gist options
  • Save zz-jason/0a58991ecbd5f070a91bc8a16017729e to your computer and use it in GitHub Desktop.
Save zz-jason/0a58991ecbd5f070a91bc8a16017729e to your computer and use it in GitHub Desktop.

C++ source 文件中的 static 和 unamed namespace

在 C 中,使用 static 关键字来限制变量或者函数只能在当前文件中使用,在 C++ 中弱化了 static 的概念,取而代之的是 unamed namespace,就像下面这样:

namespace {
int sum(int a, int b) {
  return a + b;
}
}

int avg(int a, int b) {
  return sum(a, b) / 2;
}

在这个例子中,int sum(int, int) 这个函数只能在当前文件中使用,其实上面的代码等效于下面的代码:

namespace xxxx {}

using namespace xxxx;

namespace xxxx {
int sum(int a, int b) {
  return a + b;
}
}

int avg(int a, int b) {
  return sum(a, b) / 2;
}

不要把在头文件中使用 unnamed namespace

理由也和上面一样,因为头文件会被展开到使用了他的源文件中,因此在头文件中能使用的变量在源文件中也能使用

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment