代码之家  ›  专栏  ›  技术社区  ›  Martin

使用链接库的g++编译

  •  -1
  • Martin  · 技术社区  · 6 年前

    我是新到G++的,我正在尝试编译/运行这个页面上找到的C++代码示例: https://docs.microsoft.com/en-us/windows/desktop/psapi/enumerating-all-processes

    使用编译代码

    g++ -o ex.exe ex.cpp
    

    不起作用,所以我很确定我遗漏了一些东西,比如我需要链接psapi库,或者正如代码所说的“将psapi.lib添加到targetlibs”。 我下载了所有包含的头文件并将它们放在同一个目录中,但是使用上面的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 回复  |  直到 6 年前
        1
  •  0
  •   Gmork    6 年前

    你忘了链接你的图书馆。尝试编译时使用:

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