编程语言
首页 > 编程语言> > C/C++ 静态库动态库实践

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

作者:互联网

Source File

List:

  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

Dynamic Library

Build

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

Usage

标签:__,include,lib,mylib,静态,C++,int,test,动态
来源: https://www.cnblogs.com/sonnet/p/15187479.html