This code will read the running process from OS and display it (C++). Specifically, the OS here is Windows XP. The Problem(error) is in (i think) prototype. By the way, it displays following errors.
Error 1 : error LNK2019: unresolved external symbol _EnumProcesses#12 referenced in function _main
Error 2 : error LNK2019: unresolved external symbol _GetModuleBaseNameA#16 referenced in function "void __cdecl DisplayProcessNameAndID(unsigned long)" (?DisplayProcessNameAndID##YAXK#Z)
Error 3 : error LNK2019: unresolved external symbol _EnumProcessModules#16 referenced in function "void __cdecl DisplayProcessNameAndID(unsigned long)" (?DisplayProcessNameAndID##YAXK#Z)
Error 4 : fatal error LNK1120: 3 unresolved externals C:\Documents and Settings\Windows\My Documents\Visual Studio 2008\Projects\a\Debug\a.exe
#include <afxwin.h>
#include <iostream>
#include <string.h>
#include "psapi.h"
unsigned int i;
using namespace std;
void DisplayProcessNameAndID(DWORD processID);
void main()
{
DWORD aProcesses[1024], cbNeeded, cProcesses;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return;
cProcesses = cbNeeded / sizeof(DWORD);
for ( i = 0; i < cProcesses; i++ )
{
if( aProcesses[i] != 0 )
DisplayProcessNameAndID( aProcesses[i] );
}
};
void DisplayProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID ) ;`
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
};
CString str;
str.Format("Text:%s, PID : %u", szProcessName, processID );
AfxMessageBox(str);
CloseHandle( hProcess );
}
No your issue is not with the prototype - the prototypes in windows.h are fine. If you notice your error message start with LNK which means that the linker is giving the error. This means that the linker can't find those functions.
If you look at the documentation for one of the functions that is giving the error, EnumProcessModules at the very bottom in the Library section you'll see that on Windows XP it requires linking to Psapi.lib. Visual C++ doesn't link to that library by default like it does for Kernel32.lib, which is why any functions defined in that library are fine.
You can add the Psapi.lib to the Additional Libraries section of your project, or just add the line:
#pragma comment(lib, "Psapi.lib")
To the top of the file, which will instruct the linker to use Psapi.lib.
Related
Basically I am trying create a simple FileSystem MiniFilter Driver where I can modify a notepad file from writing. Following this tutorial. So I created a project in visual studio which is type Filter Driver: NDIS. here is the full code:
/*++
Module Name:
Filter.c
Abstract:
Sample NDIS Lightweight filter driver
--*/
#include "precomp.h"
PFLT_FILTER FilterHandle = NULL;
NTSTATUS MiniUnload(FLT_FILTER_UNLOAD_FLAGS Flags);
FLT_POSTOP_CALLBACK_STATUS MiniPostCreate(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext, FLT_POST_OPERATION_FLAGS flags);
FLT_PREOP_CALLBACK_STATUS MiniPreCreate(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext);
FLT_PREOP_CALLBACK_STATUS MiniPreWrite(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext);
const FLT_OPERATION_REGISTRATION Callbacks[] = {
{IRP_MJ_CREATE,0,MiniPreCreate,MiniPostCreate},
{IRP_MJ_WRITE,0,MiniPreCreate,NULL},
{IRP_MJ_OPERATION_END}
};
const FLT_REGISTRATION FilterRegistration = {
sizeof(FLT_REGISTRATION),
FLT_REGISTRATION_VERSION,
0,
NULL,
Callbacks,
MiniUnload,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
NTSTATUS MiniUnload(FLT_FILTER_UNLOAD_FLAGS Flags) {
KdPrint(("driver unload \r\n"));
FltUnregisterFilter(FilterHandle);
return STATUS_SUCCESS;
}
FLT_POSTOP_CALLBACK_STATUS MiniPostCreate(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext, FLT_POST_OPERATION_FLAGS flags) {
KdPrint(("Post Create is running \r\n"));
return FLT_POSTOP_FINISHED_PROCESSING;
}
FLT_PREOP_CALLBACK_STATUS MiniPreCreate(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext) {
PFLT_FILE_NAME_INFORMATION FileNameInfo;
NTSTATUS status;
WCHAR Name[300] = { 0 };
status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &FileNameInfo);
if (NT_SUCCESS(status)) {
status = FltParseFileNameInformation(FileNameInfo);
if (NT_SUCCESS(status)) {
if (FileNameInfo->Name.MaximumLength < 260) {
RtlCopyMemory(Name, FileNameInfo->Name.Buffer, FileNameInfo->Name.MaximumLength);
KdPrint(("CreateFile: %ws \r\n", Name));
}
}
FltReleaseFileNameInformation(FileNameInfo);
}
return FLT_PREOP_SUCCESS_WITH_CALLBACK;
}
FLT_PREOP_CALLBACK_STATUS MiniPreWrite(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObjects, PVOID* CompletionContext) {
PFLT_FILE_NAME_INFORMATION FileNameInfo;
NTSTATUS status;
WCHAR Name[300] = { 0 };
status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &FileNameInfo);
if (NT_SUCCESS(status)) {
status = FltParseFileNameInformation(FileNameInfo);
if (NT_SUCCESS(status)) {
if (FileNameInfo->Name.MaximumLength < 260) {
RtlCopyMemory(Name, FileNameInfo->Name.Buffer, FileNameInfo->Name.MaximumLength);
_wcsupr(Name);
if (wcsstr(Name, L"OPENME.TXT") != NULL) {
KdPrint(("Write File: %ws Blocked \r\n", Name));
Data->IoStatus.Status = STATUS_INVALID_PARAMETER;
Data->IoStatus.Information = 0;
FltReleaseFileNameInformation(FileNameInfo);
return FLT_PREOP_COMPLETE;
}
KdPrint(("CreateFile: %ws \r\n", Name));
}
}
FltReleaseFileNameInformation(FileNameInfo);
}
return FLT_PREOP_SUCCESS_WITH_CALLBACK;
}
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) {
NTSTATUS status;
status = FltRegisterFilter(DriverObject, &FilterRegistration, &FilterHandle);
if (NT_SUCCESS(status)) {
status = FltStartFiltering(FilterHandle);
if (!NT_SUCCESS(status)) {
FltUnregisterFilter(FilterHandle);
}
}
return status;
}
The header files have been to precomp.h as below:
#pragma warning(disable:4201) //nonstandard extension used : nameless struct/union
#pragma warning(disable:4100)
#include <fltKernel.h>
#include <dontuse.h>
#include <suppress.h>
#include <ndis.h>
#include <filteruser.h>
#include <ntddk.h>
#include "flt_dbg.h"
#include "filter.h"
Everything else is default.
Project configuration is Active(x64) under properties.
With all of that I am getting below errors:
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol FltGetFileNameInformation referenced in function MiniPreCreate default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Warning 1324 [Version] section should specify PnpLockdown=1 to prevent external apps from modifying installed driver files. default C:\Users\Abdul\source\repos\default\default\default.inf 8
Error LNK2019 unresolved external symbol FltRegisterFilter referenced in function DriverEntry default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2019 unresolved external symbol FltUnregisterFilter referenced in function MiniUnload default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2019 unresolved external symbol FltStartFiltering referenced in function DriverEntry default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2019 unresolved external symbol FltReleaseFileNameInformation referenced in function MiniPreCreate default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2019 unresolved external symbol FltParseFileNameInformation referenced in function MiniPreCreate default C:\Users\Abdul\source\repos\default\default\filter.obj 1
Error LNK2001 unresolved external symbol FilterDriverHandle default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol FilterDriverObject default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol NdisFilterDeviceHandle default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol NdisDeviceObject default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol FilterListLock default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK2001 unresolved external symbol FilterModuleList default C:\Users\Abdul\source\repos\default\default\device.obj 1
Error LNK1120 12 unresolved externals default C:\Users\Abdul\source\repos\default\x64\Debug\default.sys 1
Can Anyone guide on what am I doing wrong?
I ran into the same issue. For me, the problem was that the mini-filter template was not showing in the templates listing for new projects and so I had to create it from scratch and I inevitably missed something. After cross-checking the linker options against the minifilter projects provided by Microsoft as reference (check here) I realized that fltMgr.lib has to be specifically provided to the linker. In order to do that right-click on the project in the "Solution Explorer" left pane. Then go to Properties->Linker->Input->Additional Dependencies. Add $(DDK_LIB_PATH)\fltMgr.lib to the list of additional dependencies and rebuild your project!
I hope this does it for you, but like the Microsoft documentation points out LNK2019 can be caused by lots of other problems with your configuration.
Trying to compile a sample http class with the SDK, and getting some strange link errors... I am sure its something to do with a missing option, or directory...
I am no expert in c++ as you can see, but looking for any assistance.
I included my sample class. I also did install the Windows SDK. If you need any other information about my setups or anything, please ask. I'd prefer someone point me to a working WinHttp SDK sample project.
//START OF utils.cpp
#pragma once
#include "stdafx.h"
class http
{
public:
http();
~http();
std::string getText();
};
//END OF utils.cpp
//START OF utils.cpp
#include "stdafx.h"
#include "utils.h"
http::http()
{
}
http::~http()
{
}
std::string http::getText()
{
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL bResults = FALSE;
HINTERNET hSession = NULL,
hConnect = NULL,
hRequest = NULL;
// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen( L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0 );
// Specify an HTTP server.
if( hSession )
hConnect = WinHttpConnect( hSession, L"www.microsoft.com",
INTERNET_DEFAULT_HTTPS_PORT, 0 );
// Create an HTTP request handle.
if( hConnect )
hRequest = WinHttpOpenRequest( hConnect, L"GET", NULL,
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE );
// Send a request.
if( hRequest )
bResults = WinHttpSendRequest( hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0,
0, 0 );
// End the request.
if( bResults )
bResults = WinHttpReceiveResponse( hRequest, NULL );
// Keep checking for data until there is nothing left.
if( bResults )
{
do
{
// Check for available data.
dwSize = 0;
if( !WinHttpQueryDataAvailable( hRequest, &dwSize ) )
printf( "Error %u in WinHttpQueryDataAvailable.\n",
GetLastError( ) );
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize+1];
if( !pszOutBuffer )
{
printf( "Out of memory\n" );
dwSize=0;
}
else
{
// Read the data.
ZeroMemory( pszOutBuffer, dwSize+1 );
if( !WinHttpReadData( hRequest, (LPVOID)pszOutBuffer,
dwSize, &dwDownloaded ) )
printf( "Error %u in WinHttpReadData.\n", GetLastError( ) );
else
printf( "%s", pszOutBuffer );
// Free the memory allocated to the buffer.
delete [] pszOutBuffer;
}
} while( dwSize > 0 );
}
// Report any errors.
if( !bResults )
printf( "Error %d has occurred.\n", GetLastError( ) );
// Close any open handles.
if( hRequest ) WinHttpCloseHandle( hRequest );
if( hConnect ) WinHttpCloseHandle( hConnect );
if( hSession ) WinHttpCloseHandle( hSession );
return "";
}
//END OF utils.cpp
1>------ Build started: Project: winagent, Configuration: Debug Win32 ------
1>Compiling...
1>utils.cpp
1>Linking...
1> Creating library C:\winagent\Debug\winagent.lib and object C:\winagent\Debug\winagent.exp
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpCloseHandle#4 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText#http##QAE?AV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpReadData#16 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText#http##QAE?AV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpQueryDataAvailable#8 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText#http##QAE?AV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpReceiveResponse#8 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText#http##QAE?AV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpSendRequest#28 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText#http##QAE?AV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpOpenRequest#28 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText#http##QAE?AV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpConnect#16 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText#http##QAE?AV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ)
1>utils.obj : error LNK2019: unresolved external symbol __imp__WinHttpOpen#20 referenced in function "public: class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __thiscall http::getText(void)" (?getText#http##QAE?AV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std##XZ)
1>C:\winagent\Debug\winagent.exe : fatal error LNK1120: 8 unresolved externals
1>Build log was saved at "file://c:\winagent\Debug\BuildLog.htm"
1>winagent - 9 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
If you check the MSDN reference for the WinHttp* functions you will see that you need to link with the library Winhttp.lib.
Open the project settings, select the linker options then 'input' and add WinHttp.lib to the 'Additional Dependencies' list.
Or you could put
#pragma comment(lib, "winhttp.lib")
(as previously mentioned) in your source code.
You need to link to winhttp.lib
Change the project settings or add this line to your .cpp file
#pragma comment(lib, "winhttp")
You've not added the WinHttp library to your link list.
Make sure you are linking with Winhttp.lib.
I've written a WinUSB project for obtaining data from spectrometer, the code seems to work few weeks ago. In the later stage I tried to link this project with CUDA, after few trials I solved the CUDA linker error. Unfortunately I ended up "error LNK2019: unresolved external symbol" in my main program(Winusb project). At first I thought it was because of the .cu files and I decided to remove all the .CU(CUDA)files form the project and still I was keep on getting the same error(LNK2019).
The following is my code for Winusb project (which was working perfectly few weeks back, but now I'm completely lost and needed some help)
Main.cpp
#include "pch.h"
#include <cstdio>
LONG __cdecl _tmain(LONG Argc, LPTSTR * Argv )
{
FILE *output_file1 = fopen("output_file2.txt", "w");
//FILE *output_file2 = fopen("output_file3.txt", "w");
DEVICE_DATA deviceData;
HRESULT hr;
USB_DEVICE_DESCRIPTOR deviceDesc;
BOOL bResult;
BOOL noDevice;
ULONG lengthReceived;
BOOL wrResult = TRUE;
BOOL wr1Result = TRUE;
BOOL RQResult = 0;
UNREFERENCED_PARAMETER(Argc);
UNREFERENCED_PARAMETER(Argv);
//////////////////////Open device ///////////////
hr = OpenDevice(&deviceData, &noDevice);
if (FAILED(hr)) {
if (noDevice) {
printf(_T("Device not connected or driver not installed\n"));
} else {
printf(_T("Failed looking for device, HRESULT 0x%x\n"), hr);
}
std::getchar();
return 0;
}
/////////////////////Get descriptor//////////////////
bResult = WinUsb_GetDescriptor(deviceData.WinusbHandle,
USB_DEVICE_DESCRIPTOR_TYPE,
0,
0,
(PBYTE) &deviceDesc,
sizeof(deviceDesc),
&lengthReceived);
if (FALSE == bResult || lengthReceived != sizeof(deviceDesc)) {
printf(_T("Error among LastError %d or lengthReceived %d\n"),
FALSE == bResult ? GetLastError() : 0,
lengthReceived);
CloseDevice(&deviceData);
return 0;
}
bool sResult = FALSE;bool syResult;
bool sResult1 = FALSE;bool syResult1;
//Initialize
UCHAR Intialize[] = {0x01};
ULONG cbISize = strlen((char*)Intialize);
ULONG InSent = 0;
wrResult = WinUsb_WritePipe(deviceData.WinusbHandle, 0x01, Intialize, 1, &InSent, 0);
//Integration time - 700ms
UCHAR Inttime[] = {0x0200100000};
ULONG cbITSize = strlen((char*)Inttime);
ULONG InttimeSent = 0;
wrResult = WinUsb_WritePipe(deviceData.WinusbHandle, 0x01, Inttime, 5, &InttimeSent, 0);
//strobe signal
UCHAR strobe1[] = {0x030001};
ULONG strobeSize1 = strlen((char*)strobe1);
ULONG strobeSent1 = 0;
wr1Result = WinUsb_WritePipe(deviceData.WinusbHandle, 0x01, strobe1, 3, &strobeSent1, 0);
//Request spectra
UCHAR Rqspectra[] = {0x09};
ULONG RqSize = strlen((char*)Rqspectra);
ULONG RqSent = 0;
RQResult = WinUsb_WritePipe(deviceData.WinusbHandle, 0x01, Rqspectra,1, &RqSent, 0);
//Pixel Values
UCHAR szBuffer[15][512];
UCHAR sz1Buffer[1];
UCHAR tBuffer[1];
ULONG tReadx;
ULONG cbReadx[16];
USHORT newbuf[15][512];
short specbu[7860];
for (int i=0;i<16;i++)
{
if (i<4)
{
sResult = WinUsb_ReadPipe(deviceData.WinusbHandle, 0x86, szBuffer[i], 512, &cbReadx[i], 0);
}
else if (i>=4 && i<15)
{
sResult = WinUsb_ReadPipe(deviceData.WinusbHandle, 0x82, szBuffer[i], 512, &cbReadx[i], 0);
}
else if (i = 15)
{
syResult = WinUsb_ReadPipe(deviceData.WinusbHandle, 0x82, sz1Buffer, 1, &cbReadx[i], 0);
}
}
int pon=0;
for (int k=0;k<15;k++)
{
for (int l=0;l<512;l+=2)
{
newbuf[k][l] = (szBuffer[k][(l+1)]<<8|szBuffer[k][l]);
specbu[pon]= (szBuffer[k][(l+1)]<<8|szBuffer[k][l]);
fprintf(output_file1,"%d\t\n",specbu[pon]);
pon++;
}
}
std::getchar();
CloseDevice(&deviceData);
return 0;
}
My Pch.h
#include <Windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <winusb.h>
#include <usb.h>
#include "device.h"
My device.h
#include
//
// Device Interface GUID.
// Used by all WinUsb devices that this application talks to.
// Must match "DeviceInterfaceGUIDs" registry value specified in the INF file.
// 390a138c-f867-4538-8fd4-46063b842d2b
//
DEFINE_GUID(GUID_DEVINTERFACE_USBApplication2,
0x390a138c,0xf867,0x4538,0x8f,0xd4,0x46,0x06,0x3b,0x84,0x2d,0x2b);
typedef struct _DEVICE_DATA {
BOOL HandlesOpen;
WINUSB_INTERFACE_HANDLE WinusbHandle;
HANDLE DeviceHandle;
TCHAR DevicePath[MAX_PATH];
}
DEVICE_DATA, *PDEVICE_DATA;
HRESULT
OpenDevice(
_Out_ PDEVICE_DATA DeviceData,
_Out_opt_ PBOOL FailureDeviceNotFound
);
VOID
CloseDevice(
_Inout_ PDEVICE_DATA DeviceData
);
My build log
1>------ Build started: Project: USB Application2, Configuration: Win7 Debug Win32 ------
1> main.cpp
1>main.obj : error LNK2019: unresolved external symbol "long __stdcall OpenDevice(struct _DEVICE_DATA *,int *)" (?OpenDevice##YGJPAU_DEVICE_DATA##PAH#Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "void __stdcall CloseDevice(struct _DEVICE_DATA *)" (?CloseDevice##YGXPAU_DEVICE_DATA###Z) referenced in function _main
1>C:\Users\bel1\Documents\Visual Studio 2012\Projects\USB Application2\Win7Debug\USBApplication2.exe : fatal error LNK1120: 2 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
========== Deploy: 0 succeeded, 0 failed, 0 skipped ==========
You will need to add source files (.CPP) into your project that are having implementation of following functions:
OpenDevice
CloseDevice
If you are using a third party library, you need to put the relevant .LIB file into Linker Input of project settings.
i am learning vc++ and checking with code for usage information of memory. this program is giving me three errors of unresolved externals..
error LNK2019: unresolved external symbol _GetProcessMemoryInfo#12 referenced
in function "void __cdecl PrintMemoryInfo(unsigned long)"
(?PrintMemoryInfo##YAXK#Z)
error LNK2019: unresolved external symbol _EnumProcesses#12 referenced in
function _main
error LNK1120: 2 unresolved externals.
Code::
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <psapi.h>
// To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
// and compile with -DPSAPI_VERSION=1
void PrintMemoryInfo( DWORD processID )
{
HANDLE hProcess;
PROCESS_MEMORY_COUNTERS pmc;
// Print the process identifier.
printf( "\nProcess ID: %u\n", processID );
// Print information about the memory usage of the process.
hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
if (NULL == hProcess)
return;
if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) )
{
printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );
printf( "\tPeakWorkingSetSize: 0x%08X\n",
pmc.PeakWorkingSetSize );
printf( "\tWorkingSetSize: 0x%08X\n", pmc.WorkingSetSize );
printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n",
pmc.QuotaPeakPagedPoolUsage );
printf( "\tQuotaPagedPoolUsage: 0x%08X\n",
pmc.QuotaPagedPoolUsage );
printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n",
pmc.QuotaPeakNonPagedPoolUsage );
printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n",
pmc.QuotaNonPagedPoolUsage );
printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage );
printf( "\tPeakPagefileUsage: 0x%08X\n",
pmc.PeakPagefileUsage );
}
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 memory usage for each process
for ( i = 0; i < cProcesses; i++ )
{
PrintMemoryInfo( aProcesses[i] );
}
return 0;
}
The header file that declares the function is used by the compiler to compile your code. The linker though does need a definition of the external functions that are used. That is typically supplied in an import library. The error message tells you that the linker has no such definition.
You have to include the respective library for psapi.h file.
#pragma comment( lib, "psapi.lib" )
EDIT::
From the MSDN-Remarks Section,
To ensure correct resolution of symbols, add Psapi.lib to the
TARGETLIBS macro and compile the program with -DPSAPI_VERSION=1.
Extra::
#pragma comment is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files.
#pragma comment(lib, libname) tells the linker to add the 'libname' library to the list of library dependencies, as if you had added it in the project properties at Linker->Input->Additional dependencies
See #pragma comment on MSDN
Try adding this
#pragma comment(lib, “psapi.lib”)
I am trying to create a simple C++ app that would search and list all .wav files on my PC. I am trying to figure out the LNK 1120 error but with no luck. Can anyone point me in the right direction with this one and tell me what am I doing wrong here?
#include "stdafx.h"
#include "iostream"
#include "Shlwapi.h"
#include "windows.h"
void FindFilesRecursively(LPCTSTR lpFolder, LPCTSTR lpFilePattern);
int _tmain(int argc, _TCHAR* argv[])
{
LPCTSTR loc = "C://";
LPCTSTR ft = ".wav";
FindFilesRecursively(loc, ft);
return 0;
}
void FindFilesRecursively(LPCTSTR lpFolder, LPCTSTR lpFilePattern)
{
TCHAR szFullPattern[MAX_PATH];
WIN32_FIND_DATA FindFileData;
HANDLE hFindFile;
// first we are going to process any subdirectories
PathCombine(szFullPattern, lpFolder, _T("*"));
hFindFile = FindFirstFile(szFullPattern, &FindFileData);
if(hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// found a subdirectory; recurse into it
PathCombine(szFullPattern, lpFolder, FindFileData.cFileName);
FindFilesRecursively(szFullPattern, lpFilePattern);
}
} while(FindNextFile(hFindFile, &FindFileData));
FindClose(hFindFile);
}
// now we are going to look for the matching files
PathCombine(szFullPattern, lpFolder, lpFilePattern);
hFindFile = FindFirstFile(szFullPattern, &FindFileData);
if(hFindFile != INVALID_HANDLE_VALUE)
{
do
{
if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
// found a file; do something with it
PathCombine(szFullPattern, lpFolder, FindFileData.cFileName);
std::cout << (_T("%s\n"), szFullPattern);
}
} while(FindNextFile(hFindFile, &FindFileData));
FindClose(hFindFile);
}
}
These are the error messages that I receive
1>------ Build started: Project: SearchForFile, Configuration: Debug Win32 ------
1>SearchForFile.cpp
1>SearchForFile.obj : error LNK2019: unresolved external symbol __imp__PathCombineA#12 referenced in function "void __cdecl FindFilesRecursively(char const *,char const *)" (?FindFilesRecursively##YAXPBD0#Z)
1>c:\users\User\documents\visual studio 2010\Projects\SearchForFile\Debug\SearchForFile.exe : fatal error LNK1120: 1 unresolved externals
> ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
The PathCombine function is in the Shlwapi.lib library, you will need to add this library to your projects linker settings.
Open your project settings and navigate to "Configuration Properties->Linker->Input" and go to the option for "Additional Dependencies" and add the library Shlwapi.lib there.