C++ "multiple definition of .. first defined here"


在C++中,經常需要include一些自己定義的頭文件,如果處理不當,很容易出現"multipe definition ....."的錯誤。

閑話少說,先來一個例子:

假設定義了如下3個文件:global.h  a.cpp b.cpp

//global.h:

#ifndef _GLOBAL_H_

#define _GLOBAL_H_

const int a=1;

int b;

#endif
//a.cpp
#include <iostream> #include <stdlib.h> #include "global.h" using namespace std; void test1() { cout<<"test1"<<endl; }
//b.cpp
#include <iostream> #include <stdlib.h> #include "global.h" using namespace std; void test2() { cout<<"test2"<<endl; }

void main()
{
cout<<"hello world"<<endl;
}

編譯:g++ -o main test1.cpp test2.cpp

提示出現錯誤:multiple definition of b....

解決方法:

1. 要是b是一個常量的話,就直接定義成const int b;即可

2. 將b定義成static, 這樣在include “global.h” 的cpp中都能修改b


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM