在我的代码中添加多个源文件和头文件的问题 [英] problem in adding multiple source and header files to my code

查看:65
本文介绍了在我的代码中添加多个源文件和头文件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Visual C ++编写一个程序.我制作了一个名为basic.h的头文件,其中包含全局变量和函数,其源文件basic.cpp包含了它们的定义.我还制作了另一个头文件matrixB.h和其源文件matrixB.cpp.Main程序和matrixB.cpp使用basic.h中的全局变量.
当我尝试编译我的代码时,出现了重新定义和缺少类型说明符的错误.如果有人知道,请帮助我.
我还已经在媒体火上上传了我的项目. http://www.mediafire.com/?o8leol9q92v1d8x


在此先感谢

Ishtiaq

I am wirting a program in visual c++.I made one header file named as basic.h which contains global variables and functions,and its source file basic.cpp contains their definitions.I have made another header file matrixB.h and its source file matrixB.cpp.Main program and matrixB.cpp uses the global variables from basic.h.
when I try to compile my code I got the errors of redefinition and missing type specifier.If anyone knows please help me.
I have also uploaded my project at media fire.http://www.mediafire.com/?o8leol9q92v1d8x


thanks in advance

Ishtiaq

推荐答案

除了Niklas所说的以外,请确保使用标头保护或#pragma once保护您的.h文件免受多重包含的侵害.
In addition to what Niklas said, make sure your .h files are protected against multiple includes by using a header guard or #pragma once.


除非您使用关键字extern然后在一个cpp文件中定义它们,否则不应在头文件中声明全局变量.如果这样做,可能会在编译两个不同的cpp文件并将它们放入其目标代码中以进行链接时描述的多个定义变量中结束.链接器将两次看到相同的变量.

通过将全局变量作为类成员(声明为静态)放在类中,可以更好地解决此问题.
You should not declare global variables in a header file, unless you use the keyword extern and then define them in one cpp file. If you do, you might end up with multiple defined variables as you describe when two different cpp files are compiled and put the variables in their object code for linking. The linker will see the same variable twice.

You could get around this in a better way by putting your global variables as class members (declared static) in a class.


这篇关于在我的代码中添加多个源文件和头文件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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