問題原因:
當(dāng)多個文件包含同一個頭文件時,并且你的.H里面沒有加上條件編譯
#ifndef test_H
#define TEST_H
#endif
就會獨立的解釋,然后生成每個文件生成獨立的標示符。在編譯器連接時,就會將工程中所有的符號整合在一起,由于,文件中有重名變量,于是就出現(xiàn)了重復(fù)定義的錯誤。
編譯報錯:
multiple definition of `xmlMemStrdup' GStreamPlayerline 75, external location: c:\mingw\lib\gcc\mingw32\4.6.2\include\c++\iostreamC/C++ Problem
multiple definition of `xmlMalloc' GStreamPlayerline 75, external location: c:\mingw\lib\gcc\mingw32\4.6.2\include\c++\iostreamC/C++ Problem
multiple definition of `forbiddenExp' CGStreamBuilder.cpp/GStreamPlayer/Src line 246C/C++ Problem
multiple definition of `xmlMallocAtomic' GStreamPlayerline 75, external location: c:\mingw\lib\gcc\mingw32\4.6.2\include\c++\iostreamC/C++ Problem
multiple definition of `emptyExp' CGStreamBuilder.cpp/GStreamPlayer/Src line 246C/C++ Problem
multiple definition of `xmlRealloc' GStreamPlayerline 75, external location: c:\mingw\lib\gcc\mingw32\4.6.2\include\c++\iostreamC/C++ Problem
multiple definition of `xmlFree' GStreamPlayerline 75, external location: c:\mingw\lib\gcc\mingw32\4.6.2\include\c++\iostreamC/C++ Problem
解決方法:
定義宏:LIBXML_STATIC
在頭文件xmlexports.h 中有如下問題:
#if defined(_WIN32) && defined(__MINGW32__)
#undef XMLPUBFUN
#undef XMLPUBVAR
#undef XMLCALL
#undef XMLCDECL
/*
* if defined(IN_LIBXML) this raises problems on mingw with msys
* _imp__xmlFree listed as missing. Try to workaround the problem
* by also making that declaration when compiling client code.
*/
#if !defined(LIBXML_STATIC)
#define XMLPUBFUN __declspec(dllexport)
#define XMLPUBVAR __declspec(dllexport)
#else
#define XMLPUBFUN
#if !defined(LIBXML_STATIC)
#define XMLPUBVAR __declspec(dllimport) extern
#else
#define XMLPUBVAR extern
#endif
#endif
#define XMLCALL __cdecl
#define XMLCDECL __cdecl
#if !defined _REENTRANT
#define _REENTRANT
#endif
#endif
其他方法:
方法1:
給每一個頭文件加上條件編譯,避免該文件被多次引用時被多次解釋,這是個應(yīng)該是習(xí)慣。這個方法會解決大部分低級問題。
方法2:
當(dāng)方法1無效時,可以把所有的全局變量放入一個頭文件 global.h (名字隨意起,但要加條件編譯)中,每一個變量前面加extern,聲明一下這些變量將在其它文件中定義。 然后建立一個和頭文件名字對應(yīng)的.c or .cpp文件 如global.c。在里面聲明所有的全局變量。例如:void(*Handl_Display)();
然后,讓涉及到全局變量的文件include ”global.h“。這樣編譯時,會先對global.c編譯生成一個global.o ,然后再和其它文件的.o鏈接生成可執(zhí)行文件。
方法3:
懶人方法,在所有的全局變量前加上static ,聲明成靜止變量。也能解決問題。