0

when i'm reading some tutorial in C programming,all of them said that we need to put only structure type declarations, function prototypes, and global variable extern declarations, in the .h file; and for the function definitions and global variable definitions and initializations we need to put them in the .c file. but when i try to put the content of the function in the header file it works fine. if it works fine why we must not use it ?
in the sum.h :

#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include<stdio.h>
#include<stdlib.h>

int sum(int a,int b)
{
    return a+b;
}

#endif // HEADER_H_INCLUDED

int the main.c:

#include "sum.h"
int main()
{
    printf("%d\n",sum(1,2));
    return 0;
}
3
  • create a sum.c file to put the code in it. compile both files & link Commented Oct 11, 2017 at 8:12
  • Try to include the header in two different files and see what happens. In c++ the inline keyword will solve the problem. Commented Oct 11, 2017 at 8:13
  • It works fine until you include the header file in two different .c files and link them together. Commented Oct 11, 2017 at 8:13

1 Answer 1

-1

Broadly, you might what to include your header in multiple source files. If you have actual function definitions in there, you're going to have multiple definitions. This will be fine until the linker tries to assemble your compiled sources into an executable or library, at which point it will fail because it finds several functions with the same name.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.