linux compile, link, static link, dynamic link

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:

gcc  -fPIC  -shared  binaryprint.c  -o   libbinaryprint.so  
Compile options.c file dynamic library
-shared This option specifies to generate a dynamic link library (let the linker generate an exported symbol table of type T, and sometimes generate an exported symbol of type W which is weakly linked), and external programs cannot be connected without this flag. equivalent to an executable file
-fPIC means compiling as position-independent code. If this option is not used, the compiled code is position-dependent, so the dynamic loading will use code copying to meet the needs of different processes, but cannot achieve the purpose of real code segment sharing.


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








Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326432069&siteId=291194637