Doubt regarding the inclusion of headers

Asked

Viewed 39 times

2

It is considered a "bad programming practice" to include a header that had already been included in another header that included?

Was it difficult to understand the doubt above? If so, please note the code below:

#tst_1.h

#ifndef TST_1_H
#define TST_1_H

//...código...e mais código...

#endif //TST_1_H

#tst_2

#ifndef TST_2_H
#define TST_2_H

#include "tst_1.h"

//...código...e mais código...

#endif //TST_2_H

#main. c

#include "tst_1.h"
#include "tst_2.h"

int main(void){

    //...faz alguma coisa...       

    return 0;
}

Observer who included tst_1.h in the main.c whereas tst_2.h had already included it within its definition.

So this is or is not a "bad programming practice" in a program written in C?

  • If each of the .h has the #ifndef or #pragma once then for many inclusions that are made only the first will be worth, so at the end of the day will be equal at the level of the final result. Good practice may already be debated.

  • As stated by @Isac in the comment, the guard condition #ifndef can be used to prevent the inclusion of duplicate header files. In terms of good practice, it is interesting to always make explicit what you want to import in terms of dependencies instead of relying on indirect dependencies. Therefore, your file main.c is in agreement. Anyone can simply hit their eye in the includes section and see that there is a dependency on the file tst_1.h without having to look at the file tst_2.h before.

1 answer

1

Thinking of good practices we have to put ourselves in the place of other programmers who will read our code.

Therefore, for them it would be easier to see a library that calls several functions or a library specific to each type of functions?

It would be much more interesting to leave each library separately specified in the main code.

Browser other questions tagged

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