C/C++教程

C/C++ 静态库动态库实践

本文主要是介绍C/C++ 静态库动态库实践,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Source File

List:

  • mylib.c
  • mylib.h
  • test.c
  1. mkdir library and cd library
  2. mkdir lib include
  3. vim include/mylib.h
#ifndef __MYLIB_H__
#define __MYLIB_H__
int qpow(int, int);
#endif /* __MYLIB_H__ */
  1. vim mylib.c
/******************************************************************************
 * File:             mylib.c
 *
 * Author:           Gsharp
 * Created:          05/15/21
 * Description:      library mylib implements
 *****************************************************************************/

#include "mylib.h"

int qpow(int a, int n) {
  int res = 1;
  if (a < 0 || n < 0) {
    return -1;
  }
  while (n) {
    if (n & 1) res *= a;
    a *= a;
    n >>= 1;
  }
  return res;
}
  1. wirte a test
#include <stdio.h>

#include "mylib.h"
int main(int argc, char *argv[]) {
  printf("%d ^ %d = %d", 3, 10, qpow(3, 10));
  return 0;
}

Static Library

Build

  1. gcc -g -Wall -Werror -fPIC -c lib/mylib.c -I./include you will get mylib.o
  2. ar rcs lib/libmylib.a mylib.o

Usage

  • gcc test.c -static -I include/ -L lib/ -lmylib -o test

Dynamic Library

Build

gcc -g -Wall -Werror -Wextra -fPIC -shared -pedantic mylib.c -o lib/libmylib.so

Usage

  • export LD_LIBRARY_PATH=./lib:$LD_LIBRARY_PATH
  • gcc test.c -I inlude/ -L lib/ -lmylib -o test
这篇关于C/C++ 静态库动态库实践的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!