您的位置:首页 > 其它

在头文件定义全局变量以后

2010-09-03 14:08 183 查看
1glo.h

#ifndef _GLO_H_
#define _GLO_H_
 
 DWORD test;
 
#endif// _GLO_H


#if !defined(AFX_1_H__7B1238F7_C7C0_49EF_8C9A_CAB897B6C2A3__INCLUDED_)
#define AFX_1_H__7B1238F7_C7C0_49EF_8C9A_CAB897B6C2A3__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "glo.h"
class C1  
{
public:
	C1();
	virtual ~C1();
    
};
#endif // !defined(AFX_1_H__7B1238F7_C7C0_49EF_8C9A_CAB897B6C2A3__INCLUDED_)


#include "glo.h"
class C2  
{
public:
	C2();
	virtual ~C2();
    
};




这样编译时 会出现error:

2.obj : error LNK2005: "unsigned long test" (?test@@3KA) already defined in 1.obj

这是为什么呢?

#ifndef #define #endif

不是可以防止头文件被重复编译,

进一步想 在编译时 是不是以.cpp文件为单位进行的,上述方法只是保证 .cpp内的头文件不被重复包含

后来我做了实验 如上述 不行

我在C1的头文件中加上#include "glo.h"

在C1的CPP中也加上#include "glo.h"

这样C1.CPP包含两个#include "glo.h" 而且"glo.h"中有DWORD 类型的定义

结果是 编译无问题 看来在编译时 是.cpp文件为单位进行的是正确的,即#ifndef #define #endif只在所在的CPP范围内起作用

而且我得出一个结论:
不要在头文件中定义变量,否则 一旦这个头文件包含在多个.CPP时 就会出现上述error

因为同一头文件中变量可以被声明多次,但只能被定义一次。







写directshow程序时,注意在定义guid 时,必须如下: Guidgen.exe , initguid.h , DEFINE_GUID
2008-05-18 16:41

// Src1.cpp #include #include "MyGuids.h" // Src2.cpp #include "MyGuids.h" // Src3.cpp #include "MyGuids.h" 其中在MyGuids.h必须使用 DEFINE_GUID(CLSID_MyObject, 0x00000000, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); (Where this example has zeroes, put the actual GUID values.) You can use the Guidgen.exe utility to create a new GUID and paste it 其中initguid.h只能在一个.cpp中包含, DEFINE_GUID()宏定义了,如果包含了一个initguid.h,那么定义一个guid, 如果没有包含一个initguid.h ,则定义一个extern guid指向定义的那个guid, 所以项目中必须有一个文件.cpp包含initguid.h,否则会出错。但如果包含了多个的initguid.h,也会出错
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: