I'm new to g++ and am trying to compile / run the example c++ code found on this page: https://learn.microsoft.com/en-us/windows/desktop/psapi/enumerating-all-processes
Compiling the code with
g++ -o ex.exe ex.cpp
Doesn't work, so i'm pretty sure I'm missing something, like I need to link the Psapi library, or as the code says "add Psapi.lib to TARGETLIBS". I downloaded all the #included header files and have them in the same directory, but compiling the file with my g++ line above leads to the following errors, which makes me think I'm forgetting something in my g++ line to include the necessary psapi lib
undefined reference to `EnumProcessModules@16'
undefined reference to `GetModuleBaseNameA@16'
undefined reference to `EnumProcesses@12'
code:
#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;
}
You forgot to link your library. Try compiling with:
g++ ex.cpp -lPsapi -DPSAPI_VERSION=1 -o ex.exe