Compile multiple C files

To compile multiple C files, you can follow these steps:

  1. Create a Makefile: A Makefile is a script that automates the compilation process. Create a file named "Makefile" in the same directory as your C files.

  2. Define targets: In the Makefile, define the targets (executable files) you want to build. Each target corresponds to a specific C file. For example, if you have two C files named "file1.c" and "file2.c", you can define two targets, such as "file1" and "file2".

  3. Write rules: For each target, write a rule that specifies how to build it. The rule typically consists of a target, dependencies (other files that the target depends on), and commands to compile the target. For example, the rule for "file1" may look like this:

file1: file1.c gcc -o file1 file1.c

This rule states that the target "file1" depends on "file1.c" and can be built by running the command "gcc -o file1 file1.c".

  1. Specify dependencies: If your C files depend on other files (such as header files), you need to specify these dependencies in the rules. For example, if "file1.c" depends on "header1.h", you can modify the rule for "file1" as follows:

file1: file1.c header1.h gcc -o file1 file1.c

This tells the compiler to rebuild "file1" whenever "file1.c" or "header1.h" is modified.

  1. Build the targets: Open a terminal, navigate to the directory containing the Makefile, and run the command "make". This will execute the Makefile and build the specified targets. For example, if you want to build "file1" and "file2", you can run:

make file1 file2

The compiler will compile each C file and generate the corresponding executable files.

  1. Run the executables: After the compilation is successful, you can run the generated executables. For example, if you have built "file1" and "file2", you can run them by executing:

./file1 ./file2

This will execute the respective C programs and produce the desired output.

By following these steps, you can compile multiple C files and generate the corresponding executables. The Makefile automates the compilation process and ensures that the targets are built correctly based on their dependencies.