makefile for creating (.so) file from existing files

后端 未结 4 1467
无人及你
无人及你 2020-12-18 10:07

I have 4 files: 1.c, 1.h, 2.c, 2.h. I need a makefile, which will create a dynamic library (.so) from tho

4条回答
  •  离开以前
    2020-12-18 10:43

    CC = gcc                                # C compiler
    CFLAGS = -fPIC -Wall -Wextra -g         # C flags
    LDFLAGS = -shared                       # linking flags
    RM = rm -f                              # rm command
    TARGET_LIB = sh_main.so                 # target lib
    
    SRCS = add.c sub.c main.c               # source file
    DEPS = header.h                         # header file
    OBJS = $(SRCS:.c=.o)                    # object file
    
    .PHONY: all
    all: ${TARGET_LIB}
    
    $(TARGET_LIB): $(OBJS)
            $(CC) ${LDFLAGS} -o $@ $^       # -o $@ says, put the output of the compilation in the file named on the left side of the :
    
    $(SRCS:.c=.d):%.d:%.c
            $(CC) $(CFLAGS) -MM $< >$@      # the $< is the first item in the dependencies list, and the CFLAGS macro is defined as above
    include $(SRCS:.c=.d)
    
    .PHONY: clean
    clean:
            -${RM} ${TARGET_LIB} ${OBJS} $(SRCS:.c=.d)
    

    After the shared library created successfully. We need to install it.
    Become the root user.
    Copy the shared library into standard directory "/usr/lib".
    Run ldcofig command.

    Recompile your .c file with shared library. root@Admin:~/C/SharedLibrary# gcc -c main.c root@Admin:~/C/SharedLibrary# gcc -o main main.o sh_main.so

    root@Admin:~/C/SharedLibrary# ldd main

    Note: In my case.
    main.c: main C file
    sh_main.so: shared library.

提交回复
热议问题