Today I've tried to use Windows API once again and encountered very time consuming case.
It's been a long time since the last time I used Windows API.
This time I've had an idea that it would be interesting to get thread associated username using Windows API. So after some time while trying to come up with something that might seemingly work. I've encountered this error:
Error
C:\Users\Windows10\Desktop\interpreter>dmd WindowsGetUserName.d
lld-link: error: undefined symbol: GetUserNameA
>>> referenced by WindowsGetUserName.obj:(_Dmain)
Error: linker exited with status 1
The Code
import std.stdio;
import core.sys.windows.windows;
import std.conv;
void main() {
char[256] userName; // Buffer to store the user name
DWORD userNameSize = userName.length; // Size of the buffer
// Call GetUserName to retrieve the user name
if (GetUserNameA(userName.ptr, &userNameSize)) {
// Successfully retrieved the user name
writeln("Logged-in user name: ", to!string(userName[0 .. userNameSize]));
} else {
// Failed to retrieve the user name
int error = GetLastError();
writeln("GetUserName failed with error code: ", error);
}
}
1. Solution
Remember to link advapi32.lib
dmd WindowsGetUserName.d -Ladvapi32.lib
rdmd -Ladvapi32.lib WindowsGetUserName.d
2. Solution
Remember to include pragma
into your source code and specify advapi32.lib
import std.stdio;
import core.sys.windows.windows;
import std.conv;
pragma(lib, "advapi32.lib");
void main() {
char[256] userName; // Buffer to store the user name
DWORD userNameSize = userName.length; // Size of the buffer
// Call GetUserName to retrieve the user name
if (GetUserNameA(userName.ptr, &userNameSize)) {
// Successfully retrieved the user name
writeln("Logged-in user name: ", to!string(userName[0 .. userNameSize]));
} else {
// Failed to retrieve the user name
int error = GetLastError();
writeln("GetUserName failed with error code: ", error);
}
}