首页 > 技术文章 > VS等待调试

gd-luojialin 2020-07-15 15:40 原文

起因:想远程调试某个程序时,不太便利。某段代码直接跑过。Sleep不靠谱。

目的:程序刚启动时,就卡住,等待VS调式器加入,设置断点,可进行单步调试。

 

#ifdef _WIN32
#include <Windows.h>
#include <debugapi.h>
#endif
#include <experimental/filesystem>

namespace fs = std::experimental::filesystem;

bool IsWaitDebug() {
#ifndef _WIN32
    return false;
#endif // OS_LINUX
    auto path = fs::u8path("D:\\XXX.ini");
    try {
        int defualtValue = 0;
        auto ret = GetPrivateProfileIntW(L"application", L"waitdebug", defualtValue, path.wstring().data());
        return ret;
    } catch (const std::exception& ex) {
        std::cout << "waitdebug error: " << ex.what() << std::endl;
    }
    return false;
}
void CheckWaitDebug() {
#ifdef _WIN32
    if (IsWaitDebug()) {
        std::cout << "Wait Debug";
        while (!IsDebuggerPresent()) {
            Sleep(1000 * 1);
        }
    }
#endif // _WIN32
}


int main() {    
    CheckWaitDebug();

   //do anything
  //.........
}

 

.ini文件

[application]
waitdebug=1

 

使用方式:创建对应的ini文件,层级目录如上。1:等待,0:不等待(或文件不存在)

 

推荐阅读