0

Can I include a first.c file into another second.c? (I am doing some socket programming to store the messages received by server in linked list so in first program I am trying to keep linked list and second program socket programming file to access the data of first in second). What kind of data in first file can be accessed in the second file? Is this is a good practice?

Please explain about the user defined .h files and give me an example for both.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    You don't want to include C file in another C file.. It's a very bad practice, and it's really ugly. – Maroun Sep 14 '14 at 06:47
  • Yes, it is possible to include a C source file in another C source file (as distinct from header files). No, you should very seldom need to do it. For a possible exception, see [How to test a static function?](http://stackoverflow.com/questions/593414/how-to-test-a-static-function/593423#593423). – Jonathan Leffler Sep 14 '14 at 06:55
  • 1
    See also [How to link multiple implementation files in C](http://stackoverflow.com/questions/15622409/how-to-link-multiple-implementation-files-in-c/) and [Should I use `#include` in headers](http://stackoverflow.com/questions/1804486/should-i-use-include-in-headers/). – Jonathan Leffler Sep 14 '14 at 07:00

1 Answers1

0

C language is a low level permissive language. If the programmer wants to do weird things the compiler won't to anything to stop it to do.

Your question is of that flavour : you can include first.c in second.c, neither the compiler nor the linker will protest. And in simple cases (only 2 source files) it will work the same. You could also rename first.c to first.h and include it. All that are simply convention ... and good practices.

Because never ever do that (except in very special cases as suggested by Jonathan Leffler). You make the separate compilation rules break in pieces. When you include a file, it is (from the compiler point of view) the same as including it in you text editor. You know you can always have a single monolithic source file, and you should know (or you will soon if you try ...) that it is hard to test and error prone because you have only 2 scopes : global and local to function, and it could easily lead to poorly structured programming.

The great ancients found better to have smaller source files, easier to write, test, and read and understand, and the include files contains the smallest part necessary to allow the separate sources to communicate : normally only declarations and constants, seldom global variables.

The conclusion is nothing more than you got in comments: yes you can, but your surely will not want to do that.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252