linux下使用vscode编译及引用动态链接库
1.动态链接库的生成
/****tasks.json*********/
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ 生成活动文件",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/lib/libcommon.so",
"-std=c++11",
"-fPIC",
"-shared"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}
在tasks.json中,动态链接库名称必须加lib,如libcommon.so,参数加-fPIC(可选),-shared(必选)。编译即可生成libcommon.so。
2.动态链接库的引用
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ 生成活动文件",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"SocketHelper.cpp",
"-o",
"${fileDirname}/${fileBasenameNoExtension}",
"-I","${fileDirname}/CommonFunc",
"-L","${fileDirname}/CommonFunc/lib",
"-l","common",
"-Wl,-rpath=${fileDirname}/CommonFunc/lib",
"-std=c++11",
"-pthread"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}
"-I":动态链接库的头文件所在目录;(大写i)
"-L":动态链接库文件所在目录;
"-l":动态链接库名(小写l);
"rpath":程序运行时,优先到rpath指定的目录去寻找依赖库; 程序链接时,在指定的目录中,隐式的链接那些动态库所需要的链接库。
特别注意"-Wl,rpath=xx",在运行调试时程序不会找"-L"参数目录下的链接库,会报错error while loading shared libraries: lib*.so: cannot open shared object file: No such file or directory。