[LINUX] Debug shared libraries with VScode

I tried to debug a shared library (.so) created in C ++ with VScode, I didn't have much information and had a hard time, so I will write it as an article.

Creating a shared library

First, create a library

g++ -shared -g -fPIC -o libtodebug.so file1.cpp file2.cpp

When compiling separately

g++ -g -fPIC -c -o file1.o file1.cpp
g++ -g -fPIC -c -o file2.o file2.cpp
g++ -shared -o libtodebug.so file1.o file2.o

Build with. You need to include the -fPIC option.

Debug with VScode

In VScode debugging, You need to configure the debug configuration file to launch an executable that uses the shared library.

launch.json


{
    //You can use IntelliSense to learn the available attributes.
    //Hover and display the description of existing attributes.
    //Check the following for more information: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python debugger",
            "type": "cppdbg",
            "request": "launch",
            "program": "python",
            "args": [
            "${Python file name for debugging, debug.py}"
            ],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                "description": "Enable pretty-printing for gdb",
                "text": "-enable-pretty-printing",
                "ignoreFailures": true
                }
            ]
        }
    ]
}

Specify a Python program as the program to debug with gdb, By loading the shared library without Python and calling the functions in the shared library from Python, It will be in the form of debugging with gdb.

Of course it doesn't have to be Python, This time I chose Python, which makes it easy to write a function that loads and executes a shared library.

Creating a Python program

Write a Python program that loads a shared library and calls a function.

debug.py


import ctypes

def main():
    sharedlib = ctypes.cdll.LoadLibrary("./libtodebug.so")
    func = sharedlib .SampleFunc
    func.argtypes = [ctypes.c_int]
    func.argtypes = [ctypes.c_int]
    res = func(ctypes.c_int(10))
    print(res)

if "__name__" == "__main__":
    main()

I feel like this. In my case, I created a GUI with tkinter and created an environment where I can debug flexibly.

Recommended Posts

Debug shared libraries with VScode
Use shared memory with shared libraries
Print debug with PyScribe
error while loading shared libraries
Install external libraries with Python
Debug Python with VS Code
Debug with PEPPER python interpreter
Steps to develop Django with VSCode
Debug email sending with Python's smtpd.DebuggingServer
Debug the script with Sakura Editor
Limit public symbols in shared libraries
I want to debug with Python
Intellisense doesn't work with tensorflow2.0 + VScode