Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active July 23, 2025 14:07
Show Gist options
  • Save scivision/ce152b9e4f252e38e7869409e3241ce2 to your computer and use it in GitHub Desktop.
Save scivision/ce152b9e4f252e38e7869409e3241ce2 to your computer and use it in GitHub Desktop.
pid_t in Windows with DWORD and no windows.h

Getting DWORD defined without Windows.h

When making platform-agnostic headers, it becomes necessary to define Windows types compatible with POSIX types and the Windows API. Here we use pid_t as an example, which on Windows may be taken as equivalent to DWORD.

Rather than include "windows.h" that is a very large header, or "windef.h" that breaks MSVC compiles, or "IntSafe.h" that includes console functions, simply apply the DWORD definition:

typedef unsigned long DWORD;

as seen in example.h.

Build and run this example

cmake -B build
cmake --build build
ctest --test-dir build -V
cmake_minimum_required(VERSION 3.19)
project(dword LANGUAGES C)
enable_testing()
add_executable(main main.c)
target_include_directories(main PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
add_test(NAME ProcessID COMMAND main)
file(GENERATE OUTPUT .gitignore CONTENT "*")
#include <sys/types.h> // for pid_t on non-Windows
#ifdef _MSC_VER
#ifndef DWORD
typedef unsigned long DWORD;
#endif
#ifndef pid_t
#define pid_t DWORD
#endif
#endif
pid_t my_get_pid();
#include <example.h>
#if defined(_MSC_VER)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <unistd.h>
#endif
#include <stdio.h>
pid_t
my_get_pid()
{
// get process ID
#if defined(_MSC_VER)
// https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocessid
return GetCurrentProcessId();
#else
// https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpid.2.html
// https://www.man7.org/linux/man-pages/man2/getpid.2.html
return getpid();
#endif
}
int main(void)
{
pid_t pid = my_get_pid();
// Print the process ID
printf("Process ID: %d\n", (int)pid);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment