lib的编写与使用(C/C++)

在C/C++中,一个完整的lib(包含一个.h和.lib)就对应一个.h和.c/.cpp。

在VS中编写lib时如果是.cpp实现的说明是C++编译实现的。那么使用的时候链接就要按照C++的链接方式(反之一样)。具体搜《extern C》的文章。

在VS中,使用lib文件时如果用配置属性绑定lib文件,注意既要指明目录,也要指明具体的.lib文件。这对应于 #pragma comment(lib, "绝对/相对路径 + 文件名.lib")。

如下两种方式:

一、lib文件用C++的方式编译

  A:lib文件的生成:

 1 //file : lib.h 
 2 #ifndef LIB_H
 3 #define LIB_H
 4 int add(int x, int y);
 5 #endif
 6 
 7 //file : lib.cpp
 8 #include"lib.h"
 9 int add(int x, int y)
10 {
11     return x+y;
12 }

  B:lib文件的使用:

1 #include "lib.h"
2 //#pragma comment(lib, "..\lib\lib_study.lib") // 也可以在VS中设置
3 int main()
4 {
5     int c = add(3,5);
6     return 0;
7 }

二、lib文件使用C的方式编译

  在VS中cpp默认都是以C++的方式进行编译的,加上 extern "C" 后改为C的编译方式,那么使用的时候也要用C的链接方式。

  A:lib文件的生成:

 1 //file : lib.h 
 2 #ifndef LIB_H
 3 #define LIB_H
 4 extern "C" int add(int x, int y);
 5 #endif
 6 
 7 //file : lib.cpp
 8 #include"lib.h"
 9 int add(int x, int y)
10 {
11     return x+y;
12 }

  B: lib文件的使用:

1 #include "lib.h"
2 //#pragma comment(lib, "..\lib\lib_study.lib") // 也可以在VS中设置
3 int main()
4 {
5     int c = add(3,5);
6     return 0;
7 }

注意:对应一、二中lib的使用包含的都是对应的.h文件,他们是不同的。

原文地址:https://www.cnblogs.com/jiangyoumiemie/p/3213572.html