How do you split C source code into separate files?

I am trying to read other people's code, but most of the code is split into separate files. I have not yet learned how to do it. How do you split the code into separate files? And how do you find the correct source code file for a function?

+4
source share
5 answers

The key method is to use “header files”, aka .h files to output “should be visible from the external” parts of each “source file”, aka .c . To search for sources in many files, see ctags , unless the IDE you use provides even better ways!

+3
source

Your functions can be declared (i.e. function return type, name and parameter types) in a ".h" file - also called a "header file".

These functions are defined (i.e. the code you write for the function) must be in the .c file.

This .c "file should have an include pointer on top. It looks like this:

 #include "myHeaderFile.h" 

Now, to find the correct source code for the function in Linux / Mac / Windows + cygwin, I would just use grep on the command line:

 grep functionName *.c 
+3
source

Take a look at using the #include preprocessor directive. #include basically inserts a copy of the file that you specify directly in the line where you place it. This allows you to modulate the source code into multiple files, but they are all compiled together.

see: http://msdn.microsoft.com/en-us/library/36k2cdd4(VS.71).aspx

+1
source

Quick note about ctags and cscope.

If your code is in a directory called src /, you can do this

 #!/bin/sh find src/ -name '*.c' > cscope.files find src/ -name '*.C' >> cscope.files find src/ -name '*.h' >> cscope.files find src/ -name '*.H' >> cscope.files ctags -R -V --c-kinds=+p --fields=+S -L cscope.files cscope -b 

Now you use ctags and vim and go directly to the main function:

 gvim -t main 

There are other good questions about what you might find in another question, so I will no longer delve into this.

/ Johan

+1
source

One source file should contain a set of (preferably close) related functions. It should provide a consistent set of services for functions outside the source file.

The source file must have an associated header that declares the services provided by the source code. (Exception: the only source file containing main() and not providing the functions used by other files does not need a header file.)

Other files that use these features include a header. The file that defines the function also includes a header to make sure the definitions match the declarations.

In general, it is a good idea for the source file to include a header first; this ensures that the header can be used as "standalone". That is, if any other source file should use the header services, it can include the header without worrying about which of the other headers should have been included first.

0
source

Source: https://habr.com/ru/post/1285643/


All Articles