在多个Cpp文件中使用变量 [英] Use variable across multiple Cpp files

查看:257
本文介绍了在多个Cpp文件中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

搜索了足够的答案,但没有一个解决方案适用于我。



场景:
我试图包括一个.h文件,



如果我将这个头文件包含在实际使用函数和变量的源文件中(精确到2),那么,最后一个编译有一个链接器错误,说明


未定义引用`abc :: myfun(char const *,char const *, char *)'


头文件中的所有函数和变量都声明为extern, >

我希望有一个cpp文件在.h文件中定义的变量中放置一个值,并且另一个cpp文件能够读取它。



如果它有帮助,我的每一段代码都在我定义的命名空间中( namespace abc {//所有文件中的所有代码}

解决方案

.h 文件中的声明确切地说,让编译器知道 您计划在某处计划的对象。 某处将是一个编译单元( .c .cpp 文件)



code> foo.h :

  extern int global_foo; 

foo.c

  #includefoo.h
int global_foo; //可选你可以这样初始化:int global_foo = 123;

main.c

  #includefoo.h
void bar()
{
global_foo = 0; //访问该文件外部的变量

不会意外嵌套命名空间,因为 abc :: something 不等于 abc :: abc :: something


Have searched enough answers but none of the solutions work for me.

scenario : I am trying to include a .h file that has some functions declared (not defined) and some variables declared.

If I include this header file in the source files (2 to be precise) that actually use the functions and variables, then the last one that compiles has a linker error that states

undefined reference to `abc::myfun(char const*, char const*, char*)'

All the functions and variables in the header files have been declared as extern and include guards are present.

I wish to have one cpp file put a value in the variable defined in the .h file and another cpp file to be able to read it.

Also if it helps, every piece of my code is in a namespace that I have defined ( namespace abc{ //all my code, in all the files } )

解决方案

Declarations in your .h file are doing exactly that - letting compiler know of the objects you are planning on declaring "somewhere". That "somewhere" would be a compilation unit (a .c or .cpp file) where that variable would be defined.

Here's an example (skipping the guards for simplicity):

foo.h:

extern int global_foo;

foo.c:

#include "foo.h"
int global_foo; // optionally you can initialize like this: int global_foo = 123;

main.c:

#include "foo.h"
void bar()
{
  global_foo = 0; // accessing that variable which is "outside" of this file

As paddy mentioned above - make sure you are not accidentally nesting namespaces, since abc::something is not the same as abc::abc::something

这篇关于在多个Cpp文件中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆