简体   繁体   中英

ABOUT HEADER FILE CREATION ERROR IN C++

i'm creating header file for .cpp file,where it will contain only declaration or prototype of function

here is the threes programs i have written 1.header.h file//where i have declared functions add( , ) and sub( , )

 #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,where i have defined functions add( , ) and sub( , )

 #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();
      }

here, i declared variable 's' in header.h and defined in header.cpp file ,which is given as addition to variable c in example.cpp file output.

it showing error header.obj : error LNK2005: "int s" (?s@@3HA) already defined in example.obj Projects\\header\\Debug\\header.exe : fatal error LNK1169: one or more multiply defined symbols found please help me to resolve this error,i'm working from long time for this...thanks in advance

You get the error, because this line in .h is already a definition :

int s;

You need to have this in header:

extern int s;

And then in exactly one .cpp file, usually one with same base file name as the .h file, you need to have the definition:

int s;

Related: You don't need the extern keyword with function declarations, because they're just declarations, telling compiler that such a function exists somewhere, and you can do that as many times as you like. But if you put a global (non- static , non- inline ) function definition (with {} function body instead of ; ) to a .h file, you do get similar linker error about multiple definitions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM