带链接库的g ++编译

时间:2019-02-16 19:16:55

标签: c++ g++ libraries .lib psapi

我是g ++的新手,正在尝试编译/运行此页面上的示例c ++代码: https://docs.microsoft.com/en-us/windows/desktop/psapi/enumerating-all-processes

使用

编译代码
g++ -o ex.exe ex.cpp

不起作用,所以我可以肯定我缺少一些东西,例如我需要链接Psapi库,或者代码显示为“将Psapi.lib添加到TARGETLIBS”。 我下载了所有#include头文件,并将它们放在相同的目录中,但是使用上面的g ++行编译该文件会导致以下错误,这使我认为我忘记了我的g ++行中的某些内容,其中包括必需的psapi库

undefined reference to `EnumProcessModules@16'
undefined reference to `GetModuleBaseNameA@16'
undefined reference to `EnumProcesses@12'

代码:

#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <psapi.h>

// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1

void PrintProcessNameAndID( DWORD processID )
{
    TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");

    // Get a handle to the process.

    HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                                   PROCESS_VM_READ,
                                   FALSE, processID );

    // Get the process name.

    if (NULL != hProcess )
    {
        HMODULE hMod;
        DWORD cbNeeded;

        if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), 
             &cbNeeded) )
        {
            GetModuleBaseName( hProcess, hMod, szProcessName, 
                               sizeof(szProcessName)/sizeof(TCHAR) );
        }
    }

    // Print the process name and identifier.

    _tprintf( TEXT("%s  (PID: %u)\n"), szProcessName, processID );

    // Release the handle to the process.

    CloseHandle( hProcess );
}

int main( void )
{
    // Get the list of process identifiers.

    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
    {
        return 1;
    }


    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the name and process identifier for each process.

    for ( i = 0; i < cProcesses; i++ )
    {
        if( aProcesses[i] != 0 )
        {
            PrintProcessNameAndID( aProcesses[i] );
        }
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

您忘记链接您的图书馆。尝试使用:

g++ ex.cpp -lPsapi -DPSAPI_VERSION=1 -o ex.exe