Ir para o conteúdo

Última atualização:2026-10-12

Depuração de programas C++ com LLDB

Este artigo mostrará como usar o depurador LLDB para depurar um programa C++ simples. Nosso código de exemplo chama-se test.cpp.

#include <iostream>
#include <string>

struct MyStruct {
    int myInt;
    std::string myString;
};

int main() {
    MyStruct myStruct;
    myStruct.myInt = 42;
    myStruct.myString = "Hello, world!";

    int sum = 0;
    for (int i = 1; i <= 5; ++i) {
        sum += i;
    }

    return 0;
}

Compilação

Primeiro, precisamos compilar o código com a flag -g para habilitar informações extras de depuração.

clang++ -g test.cpp -o test

Iniciando a depuração

Em seguida, anexamos o depurador.

lldb test

Breakpoints

Definimos o breakpoint na função main().

(lldb) b main

Saída:

Breakpoint 1: where = test`main + 19 at test.cpp:10:14, address = 0x0000000100003be3

Execução

Depois, iniciamos o processo.

(lldb) run

Saída:

Process 11333 launched: '/Users/light/test' (x86_64)
Process 11333 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x0000000100003be3 test`main at test.cpp:10:14
   7    };
   8    
   9    int main() {
-> 10       MyStruct myStruct;
   11       myStruct.myInt = 42;
   12       myStruct.myString = "Hello, world!";
   13  

Verificando os breakpoints

Agora, estamos parados no início da função main(). Podemos definir breakpoints em linhas específicas.

(lldb) b 16

Saída: Breakpoint 2: where = test`main + 76 at test.cpp:16:16, address = 0x0000000100003c1c

Para listar os breakpoints definidos no momento, use o comando a seguir.

(lldb) breakpoint list

Saída:

(lldb) breakpoint list
Current breakpoints:
1: name = 'main', locations = 1, resolved = 1, hit count = 1
  1.1: where = test`main + 19 at test.cpp:10:14, address = 0x0000000100003be3, resolved, hit count = 1 

2: file = '/Users/zhangxing/test.cpp', line = 16, exact_match = 0, locations = 1, resolved = 1, hit count = 0
  2.1: where = test`main + 76 at test.cpp:16:16, address = 0x0000000100003c1c, resolved, hit count = 0 

Continuando a execução do programa

Podemos continuar a execução do programa até o próximo breakpoint.

(lldb) c

Saída:

Process 11823 resuming
Process 11823 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 2.1
    frame #0: 0x0000000100003c1c test`main at test.cpp:16:16
   13   
   14       int sum = 0;
   15       for (int i = 1; i <= 5; ++i) {
-> 16           sum += i;
   17       }
   18   
   19       return 0;

Imprimindo variáveis

Para obter o valor da variável local atual, você pode usar o seguinte comando:

(lldb) p myStruct

Saída:

(MyStruct) $0 = (myInt = 42, myString = "Hello, world!")

Watchpoints

Para monitorar alterações no valor de uma variável específica, podemos usar watchpoints.

(lldb) watch set variable sum

Saída:

Watchpoint created: Watchpoint 1: addr = 0x7ffeefbff1e8 size = 4 state = enabled type = w
    declare @ '/Users/zhangxing/test.cpp:14'
    watchpoint spec = 'sum'
    new value: 0

Após executar next, você verá a mudança registrada pelo watchpoint.

(lldb) n

Watchpoint 1 hit:
old value: 3
new value: 6
Process 11823 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = watchpoint 1
    frame #0: 0x0000000100003c25 test`main at test.cpp:15:29
   12       myStruct.myString = "Hello, world!";
   13   
   14       int sum = 0;
-> 15       for (int i = 1; i <= 5; ++i) {
   16           sum += i;
   17       }
   18   

Se quiser interromper a execução com base em uma condição, é possível definir uma condição de parada.

(lldb) watch modify -c '(sum > 5)'

Saída:

Watchpoint 1 hit:
new value: 6
Process 12848 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = watchpoint 1
    frame #0: 0x0000000100003c25 test`main at test.cpp:15:29
   12       myStruct.myString = "Hello, world!";
   13   
   14       int sum = 0;
-> 15       for (int i = 1; i <= 5; ++i) {
   16           sum += i;
   17       }
   18   

Concluída a depuração, você pode continuar a execução do programa.

(lldb) c

Para mais informações, consulte a documentação do LLDB:


Com esses passos, você pode depurar facilmente os seus programas C++ com o LLDB, encontrando bugs e resolvendo problemas.

Tópicos relacionados

Comentários