我創建頭文件的.cpp文件,它僅包含聲明或功能關於C頭文件創建錯誤++
這裏的原型是三分節目我已經寫 1.header.h文件//其中i已聲明的函數添加(,)和子(,)
#ifndef HEADER_H
#define HEADER_H
#pragma once
int s;
int add(int a,int b);
int sub(int a,int b);
#endif
2.header.cpp,其中i已定義函數添加(,)和子(,)
#include<iostream>
#include "header.h"
using namespace std;
int add(int a,int b){
s=10;
int c=a+b+s;
return c;
}
int sub(int a,int b){
int c=a-b;
return c;
}
3.example.cpp
#include<iostream>
#include"header.h"
using namespace std;
void main(){
int a=10,b=20;
int c=add(a,b);
int d=sub(c,a);
cout<<"c"<<c;
cout<<"d"<<d;
//cout<<s;
getchar();
}
在這裏,我聲明的變量 's' 的在header.h和header.cpp文件,它被給定爲除了在變量c定義example.cpp文件輸出。
它表示錯誤 header.obj:錯誤LNK2005: 「的int」(α[email protected]@ 3HA)在example.obj 已經定義項目\頭\調試\爲header.exe:致命錯誤LNK1169:一個或多個多重定義符號找到 請幫我提前......解決這個錯誤,我從很長一段時間這方面的工作的感謝
如果你使用include guard #define,我覺得把#pragma once放在裏面是沒有意義的...... – hyde
但是我在互聯網上看到#pragma的用法會保持優化代碼執行, ,你的意思是說我只能寫,#ifndef #pragma ..endif,對吧? – Santhosh
不,##ifndef和#define會像你一樣走到一起。 '#pragma once'是一個非標準的*替代*,可以減少一些編譯器的編譯時間。它不會以任何方式影響代碼執行。你應該把它放在[include guard]之外(http://en.wikipedia.org/wiki/Include_guard),或者根本不使用它。 – hyde