我是新到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;
}