具有外部链接的命名空间
我遇到的问题与greentype"在http://www.cplusplus.com/forum/beginner/12458/
The problem I have is basically the same as 'greentype' mentions at http://www.cplusplus.com/forum/beginner/12458/
我通过命名空间共享变量,当我尝试将函数定义放入单独的文件时出现问题.
I'm sharing variables through namespaces and a problem arises when I try to put my function definitions into a separate file.
考虑下面的例子,我想传递变量'i',定义在主代码中,到函数a():
Consider the following example, where I want to pass variable 'i', defined in the main code, to the function a():
* nn.h: *
#ifndef _NN_H_
#define _NN_H_
namespace nn {
int i;
}
#endif
* main.cpp *
#include <iostream>
#include "nn.h"
using namespace std;
using namespace nn;
void a();
int main()
{
i=5;
a();
}
void a()
{
using namespace std;
using namespace nn;
i++;
cout << "i = " << i << endl;
}
<小时>
但是现在如果我把 a() 的定义放到一个单独的文件中...
But now if I put the definition of a() into a separate file ...
* a.cpp *
#include <iostream>
#include "nn.h"
void a()
{
using namespace std;
using namespace nn;
i++;
cout << "i = " << i << endl;
}
<小时>
...然后在链接时出现多重定义"错误(g++ main.cppa.cpp -o 主要).如果我在头文件extern"中声明i"(如在其他论坛中建议),我得到未定义的参考"错误.当 'i' 在标头中声明为 const 时,我可以编译,但这不是我想要的.
... then I get 'multiple definition' error when linking (g++ main.cpp a.cpp -o main). If I make 'i' declaration in the header file 'extern' (as suggested in other forums), I get 'undefined reference' error. I can compile when 'i' is declared as const in the header, but that's not what I want.
非常感谢任何建议.
推荐答案
任何全局对象,例如 i
,都必须在程序的某处有一个定义,但可以声明 多次.
Any global object, like i
, must have exactly one definition somewhere in the program, but it can be declared multiple times.
使用没有初始化器的 extern
使声明只是一个声明.这适用于您的头文件,但您仍必须在某处定义 i
.除了制作标头声明 extern
之外,您还需要将定义(即不带 extern
的声明副本)添加到您的一个且只有一个源文件中.
Using extern
without an initializer makes a declaration just a declaration. This is appropriate for your header file, but you must still define i
somewhere. As well as making the header declaration extern
you also need to add a definition (i.e. a copy of the declaration without extern
) to one and only one of your source files.
阅读您的问题,您说您想将变量传递给函数.从样式和代码结构的角度来看,这通常不是使用共享(全局)变量的好理由.在没有任何重要原因的情况下,您通常应该定义一个函数,该函数接受一个参数并通过其参数将一个值(可能来自局部变量)从调用站点传递给该函数.
Reading your question, you say that you want to pass a variable to a function. From a style and code structure point of view, this isn't usually a good reason for using a shared (global) variable. In the absence of any overriding reasons you should normally define a function which takes a parameter and pass a value (possibly from a local variable) from the calling site to that function via its parameter.
相关文章