3 files, main.c binaryprint.h binaryprint.c
What the function does: Print the binary form of an integer.
binaryprint.h
void binaryprint(int a);
binaryprint.c
#include <stdio.h> #include "binaryprint.h" void binaryprint(int a) { int count = 32; while (count--) { if (1 << count & a) printf("1"); else printf("0"); if (count % 8 == 0) printf(" "); } printf("\n"); }
main.c
#include <stdio.h> #include "binaryprint.h" intmain() { binaryprint(1); binaryprint(8); binaryprint(1024); return 0; }
Compile: gcc -c main.c binaryprint.c
After ls, I found two more files main.o binaryprint.o
Link: gcc -o main main.o binaryprint.o
Execute: ./main
Static link:
ar rc libbinaryprint.a binaryprint.o
libbinaryprint.a is the generated static library file, lib is the prefix, .a is the suffix, in fact, the .o files are packaged together
gcc -o main2 main.o -L./ libbinaryprint.a 或者 gcc -o main2 main.o -L./ -lbinaryprint
-L./ indicates that the static library file is in the current folder -l option can omit the prefix and suffix
Then ./main2 will do
Dynamic link:
Add the dynamic library file to the library search path,
method 1:
Usually in /lib or /user/lib
sudo cp /home/xx/libbinaryprint.so /lib
gcc -o main2 main.o -L./ libbinaryprint.so
Then ./main2 will do
method 2;
Modify the LD_LIBRARY_PATH environment variable and add the path to the library file
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/xx
gcc -o main3 mian.o -L./ libbinaryprint.so
Then ./main3 will do