How to use . h files in c language?

Asked

Viewed 10,254 times

1

I would like to know which is the most recommended use of the files *.h? Because I don’t know if I can use them just to get the prototype of the functions or the full function.

1 answer

2


Most . h files serve only to reference a method that is in a . c, . a , . so, . o or . dll, plus it doesn’t stop you from putting the features inside them, it’s just not semantically correct. an example for use is like this...

file. h

#ifndef  FILE_H
#define  FILE_H

    #include <stdio.h>
    #include <malloc.h>
    #include <stdarg.h>
    #include <unistd.h>
    #include <string.h>

    void method_01(void);
    int method_02(int , int);
    const char * method_return_string();

#endif  /*FILE_H*/

file. c

#include "file.h"

void method_01(void){
    puts("method called...");
}

int method_02(int x, int y){
    return x+y;
}

const char method_return_string(){
    char *c = (char*) malloc(sizeof(char)*60);
    strcat(c,"my text");

    return c;
}
  • "but that doesn’t stop you from putting the features inside them". I believe that "features" here refers to the settings. If you put the definitions in a file . h and include that file . h in several sources . c, for the same project, the compiler will accuse multiple definitions for the same function

  • This would happen even without the functionality, so you should put macros at the beginning of the file, #ifndef , #if !defined() or #pragma once, this will cause multiple definitions not to occur.

  • No, I don’t think you understand me. The #ifndef , #if !defined() or #pragma once prevents you from making multiple inclusions in the same file. Like, if you have a font that does an x and y file include and Y includes x again, this directive protects this. What I’m talking about is separate files (separate sources, or separate compilation drives). These guards do not protect these multiple settings.

  • right, I think I understand what you mean, the source is imported to both files, but if you include it in only one file, there is no problem at this point, it does not prevent you from using in this way.

  • 1

    The use of . h in just one . c is only used in simple examples. If you increase the complexity a little bit, it starts to give problem. In fact, the . h serves to separate the declaration of a name from its definition (.c) and to avoid these multiple redefinitions that I am commenting on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.