A Simple Makefile in C: Naming Object Files Differently
Problem: When compiling C programs, it's often desirable to name the resulting object files differently from the source files. This can be useful for organization, especially when dealing with large projects.
Rephrased: Let's say you have a C file called my_module.c
, but you want the compiled object file to be named my_module_obj.o
instead. How do you achieve this using a Makefile?
Scenario & Original Code:
Let's assume we have a simple C file named my_module.c
:
// my_module.c
#include <stdio.h>
void my_function() {
printf("Hello from my_module!\n");
}
A basic Makefile might look like this:
all: my_module.o
gcc my_module.o -o my_module
my_module.o: my_module.c
gcc -c my_module.c -o my_module.o
Analysis & Clarification:
This Makefile compiles my_module.c
into my_module.o
and then links it to create the final executable my_module
. However, we want the object file to be named my_module_obj.o
.
Solution:
We can achieve this by simply modifying the my_module.o
target rule in the Makefile:
all: my_module_obj.o
gcc my_module_obj.o -o my_module
my_module_obj.o: my_module.c
gcc -c my_module.c -o my_module_obj.o
Explanation:
my_module_obj.o
target: We've changed the target object file name frommy_module.o
tomy_module_obj.o
in both theall
andmy_module_obj.o
rules.- Dependency: The
my_module_obj.o
target still depends onmy_module.c
, ensuring that the object file is rebuilt if the source file changes. - Compilation: The
gcc -c my_module.c -o my_module_obj.o
command explicitly tells the compiler to create the object file with the desired name.
Additional Value:
Naming object files differently can be beneficial for:
- Organization: It helps keep related code together and distinguishes between different modules within a project.
- Versioning: Using unique names for object files allows for easy identification of different versions of code.
- Debugging: Having separate object files can aid in debugging by making it easier to pinpoint the source of errors.
Example:
Let's assume you have another source file named main.c
:
// main.c
#include <stdio.h>
#include "my_module.h"
int main() {
my_function();
return 0;
}
Your Makefile can now be updated to include both source files and compile them separately:
all: main.o my_module_obj.o
gcc main.o my_module_obj.o -o my_module
main.o: main.c
gcc -c main.c -o main.o
my_module_obj.o: my_module.c
gcc -c my_module.c -o my_module_obj.o
Conclusion:
By simply adjusting the target object file name in your Makefile, you can easily create object files with different names from their corresponding C files. This provides greater control over your project's organization and helps you manage larger and more complex codebases.
Resources: