1

I'm trying to learn the use of header files in C. Now I found few resources in my research but none of them created the desired effect.

First, according to this tutorial, I can write my functions in the header file itself. But I don't want to do that. I want to keep the header file unchanged even if I changed the code given that the interface remains unchanged.

Answer to this question suggests two methods. First I can write the code and header file separately and include them when I compile as follows:

gcc -o myprog test.c library.c

But I don't want to do that either. My library functions should be readily available without needing to include in compile line. According to the same answer, I could create a library and then link to it with -l switch. But when it comes to functions like printf, you don't need to do either of them. All you have to do is to include the header files.Is there any way of doing that?

summary for TL;DR

I want to write a library in C which:

  1. Doesn't have to be implemented in the header file itself.

  2. Doesn't have to be included in the compile line every time I use the library functions.

  3. Doesn't have to be linked with -l every time I use the library function.

  4. Basically the library should be used by only including the header file.

Is there anyway that I could do it in Linux?

Community
  • 1
  • 1
Math4lyf
  • 33
  • 3
  • In the old days, before shared libraries became the norm, you could add your code to the system C library. It was never a good idea; any update to the system library would throw away your additions. But it could be done. Otherwise, you have to find a way to configure your C compiler to run the linker to link your library automatically, like it links the system C library automatically. That's probably doable; it isn't worth the effort, though. (Again, changes to the compiler will probably mean you have to make the changes each time you update the compiler.). You should simply use `-lwhatever`. – Jonathan Leffler Nov 06 '16 at 06:39

1 Answers1

2

But when it comes to functions like printf, you don't need to do either of them. All you have to do is to include the header files.Is there any way of doing that?

Short answer is "no". Long answer is that C compiler links some libraries "for free", including the library that implements printf.

You have an option to decline these "freebies" - in gcc it's -nodefaultlibs. If you add this option, printf would be missing.

Note: One thing that headers can implement is macros. However, macros do not behave like normal functions, so you should approach them with great caution.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523