我是g ++的新手,我正在尝试编译/运行此页面上的示例c ++代码:https://docs.microsoft.com/en-us/windows/desktop/psapi/enumerating-all-processes
使用编译代码
g++ -o ex.exe ex.cpp
不起作用,所以我很确定我缺少一些东西,比如我需要链接Psapi库,或者代码说“将Psapi.lib添加到TARGETLIBS”。我下载了所有#included头文件并将它们放在同一目录中,但是用上面的g ++行编译文件会导致以下错误,这让我觉得我忘记了我的g ++行中包含必要的psapi lib的东西
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;
}
你忘了链接你的图书馆了。尝试编译:
g++ ex.cpp -lPsapi -DPSAPI_VERSION=1 -o ex.exe