Home > Software engineering >  Should I #include a library header?
Should I #include a library header?

Time:04-12

Suppose I want only one (or a few) function from a certain header but it's a function I can define with the same efficiency as the library's implementation. Should I include a library header or implement my own function? Which is better?

I'm learning my first language C and I'm loving it.

EDIT:

Most of you didn't get the question. Forget about portability, and if it makes you happy "assume" that I can make a function with exactly the same efficiency. Or let's just say I've got the same implementation somehow.

I read somewhere that

The #include directive tells the preprocessor to open a specified file and insert its contents into the current file.

The header like <stdlib.h> consists of many things so I wonder whether inserting all it's content to the file, or inserting a custom header with just what I want, which is more efficient in terms of speed or memory or program size?

CodePudding user response:

and welcome to Stack Overflow. First let me say that what you are asking about generally doesn't happen. Libraries are generally created to prevent re-writing large amounts of code. However, if it did happen, the first thing to consider is portability.

While it's not entirely accurate, we can make the assumption that deployed software is more likely to be maintained than the program you wrote. If a change needs to be made with that software, you will end up pulling in that change after updating your system and re-compiling.

If on the other hand, if you determine, that even if something changed, you wouldn't want it to, then by all means implement it yourself. Assuming your code is as efficient as the library, there isn't going to be a performance difference.

CodePudding user response:

I think that as you're learning, you should do the following two things, in order:

  1. Implement and test your home-grown function
  2. See how the library function differs from your implementation

Library functions are not always the "best" solution: They're the best in general, not necessarily the most efficient.

Although I rely on libraries almost exclusively in my work, I started, as many programmers do, with a lot of home-grown (and buggy) equivalents to standard library functions. Writing that code has helped me become a better programmer.

CodePudding user response:

Yes, use the already written, and presumably much better tested version.

I can define with the same efficiency as the library's implementation

You are mistaking. I don't care if you're Kernighan or Ritchie or whoever, you will not write code even half as optimized as your compiler's standard library. You will have bugs you need to fix and as such you will never be able to trust your standard library when something crashes, so you'll always have to debug it as well.

  • Related