Search code examples
clinkerprecompiled-headers

Is it ok to store functions in header files that aren't shared across multiple source files?


What if you have a minimal amount of structures, functions and macros but want to exclude them from the source file to convert the source code into a more concise and readable format and reduce the amount of lines of code.

Is structures, functions or macros/data in general accessible/viewable from examining the binary even if the data is not called within the source code? And if so how?

For the sake of readability is it safe to cut structures, functions and macros from a source file into a header file that is used by multiple source files even if some source files don't use all of the structures, functions and macros (for small header files)?


Solution

  • Is structures, functions or macros/data in general accessible/viewable from examining the binary even if the data is not called within the source code?

    Depends on what you build. If you build a library (.a, .so, .lib, .dll, whatever) they're probably in there and everything in that library is accessible in some way. If you build an executable the linker will most likely remove unused code.

    Have a look at nm

    For the sake of readability is it safe to cut structures, functions and macros from a source file into a header file that is used by multiple source files

    Yes and no. Put declarations of functions/structs in header files and their implementations in .c files. Don't put a lot of unrelated functions and structs in one header. You end up including all those declarations in every source file even though you're using 5% of them. That means extra work for your compiler, probably some extra work for your linker and extra work for your and future programmers brains when reading all this unnecessary stuff.

    So, guessing what's happening in your code base, you probably want to put them in seperate header files.

    Be careful when using macros and even more when putting them in header files. You should avoid this most of the time.

    even if some source files don't use all of the structures, functions and macros

    That is quite common. You include some standard C headers too and don't use all of the functions and structs in there right? Just (as I said) put together what belongs together.