In this article, we will guide you through the process of creating a C program that adds two numbers, with the addition functionality implemented in a separate file. We will compile the addition function as a shared library and link it to the main program.
First, we need to create the main program that will use the Add function to add two numbers. Save the following code in a file named main.c:
#include <stdio.h>
#include "add.h"
int main() {
int num1, num2, sum;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
sum = Add(num1, num2);
printf("Sum: %d\n", sum);
return 0;
}
Next, we create the file that contains the implementation of the Add function. Save the following code in a file named add.c:
int Add(int a, int b) {
return a + b;
}
We also need a header file to declare the Add function so it can be used in main.c. Save the following code in a file named add.h:
#ifndef ADD_H
#define ADD_H
int Add(int a, int b);
#endif
We will compile add.c into a shared object file (.so). Open a terminal (or command prompt) and navigate to the directory where the files are saved. Then, run the following commands:
gcc -fPIC -c add.c -o add.o
gcc -shared -o libadd.so add.o
- The
-fPICoption generates position-independent code, which is required for shared libraries. - The
-sharedoption creates a shared object file from the compiled object file.
Now, we need to compile main.c and link it with the shared library we created. Run the following command:
gcc -o add_numbers main.c -L. -ladd
- The
-L.option tells the compiler to look in the current directory for libraries. - The
-laddoption tells the compiler to link with the library namedlibadd.so.
To ensure the shared library can be found when running the program, you may need to set the LD_LIBRARY_PATH environment variable. Run the following command:
export LD_LIBRARY_PATH=.
Finally, run the compiled program:
./add_numbers
The program will prompt you to enter two integers and then output their sum.