Edward De Jong
Edward De Jong

Reputation: 181

How to get Visual Studio Code on Linux to link with a shared library?

//  This is my tasks.json file, i am trying to link to 2 shared libraries, which are in the /usr/lib64 folder
{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: gcc build active file",
            "command": "/usr/bin/gcc",
            "args": [
                "-std=c99",
                "-g",
                "${fileDirname}/*.h",
                "${fileDirname}/*.c",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "-L/usr/lib64/",
                "-llibpthread",
                "-llibpcap"
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

I have tried using -l/usr/lib64/libpthread, and pthread.so, etc., all different combinations, but it says:

Starting build...
Build finished with errors(s):
/usr/bin/ld: cannot find -llibpthread
/usr/bin/ld: cannot find -llibpcap
collect2: error: ld returned 1 exit status

I know I am very close, but no cigar on the build. I am not using Cmake, and just compiling a few files manually in Visual Studio Code on Centos 7 version of Linux.

Upvotes: 1

Views: 2817

Answers (1)

Edward De Jong
Edward De Jong

Reputation: 181

Firstly, the linker automatically prepends a 'lib' prefix to linked files. So the working JSON is:

            "args": [
                "-std=c99",
                "-g",
                "${fileDirname}/*.h",
                "${fileDirname}/*.c",
                "-L/usr/lib64/",
                "-lpthread",
                "-lpcap",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"

So the trick is to first specify the library folder the -L option (/usr/lib64/) then use the -l option for each library you want, omitting the lib prefix (file is actually called libpthread.so). Sure wish they documented this better!

Hopefully this will help someone. I wasted hours on this.

Upvotes: 2

Related Questions