Building¶
# Windows 2000/XP sysroot (msvcrt.dll)
make BIN=/path/to/llvm/bin SYSROOT=/path/to/sysroots/win2k-xp
# Any of win32-sdk's clang config files, such as picolibc (no C runtime DLL)
make BIN=/path/to/llvm/bin CFG=/path/to/cfg/win32-picolibc.cfg
# Stock clang with Ubuntu's MinGW-w64 and libstdc++
make TARGET=i686-w64-mingw32 STDLIB=
The libraries go to build/<triple> (or build/<config name>): the
static libraries libmfc.a and libmfcu.a (Unicode), and the shared
library, mfc.dll and mfcu.dll (see below). make static builds only
the static ones. make install PREFIX=dir copies the headers to
dir/include/mfc, the libraries to dir/lib and the DLLs to dir/bin
(for Linux and macOS, see below).
A program then needs only the include path and the library path:
clang++ --config=winxp.cfg -Ipath/to/mfc/include app.cpp app-res.o \
-Lpath/to/build/i586-pc-windows5.1-gnu -mwindows -o app.exe
As with Visual C++, afx.h names the libraries to link, so no -l
options are needed: mfc or mfcu by _UNICODE, and user32, gdi32,
comdlg32, comctl32, shell32, advapi32, winspool, ole32,
oleaut32 and uuid (afxsock.h adds ws2_32, afxinet.h adds
wininet, afxole.h adds oledlg and urlmon, and afxdb.h adds
odbc32).
Define _AFX_NOFORCE_LIBS to turn that off. The library provides
WinMain (and wWinMain), so Unicode programs link with or without
-municode.
A regular DLL (an MFC DLL with a CWinApp of its own, such as a
control's .ocx) builds the same way with -shared and a .def file
for its exports:
clang++ --config=winxp.cfg -Ipath/to/mfc/include -shared ctl.cpp ctl.def ctl-res.o \
-Lpath/to/build/i586-pc-windows5.1-gnu -o ctl.ocx
The library provides its DllMain, which starts the DLL's CWinApp
(InitInstance) when it loads and ends it (ExitInstance) when it unloads,
so such a DLL does not write one; _AFX_NO_DLLMAIN turns that off. The
DLL has its own copy of the library, with its own instance handle,
resources, window classes and window objects, so AFX_MANAGE_STATE has
nothing to do and the program and the DLL need not use the same
library build. AfxDllGetClassObject, AfxDllCanUnloadNow and
COleObjectFactory::UpdateRegistryAll implement the usual exports.
A regular DLL can use mfc.dll instead (see below): build it with
-D_AFXDLL -D_USRDLL, as Visual C++ does. It then shares the library
with the program but keeps a module state of its own (its CWinApp,
instance and resource handles, window classes, window objects and OLE
factories), and each function it exports starts with
AFX_MANAGE_STATE(AfxGetStaticModuleState()), which makes that state
the current one until the function returns. The DLL's windows and COM
objects switch to it themselves.
Linux and macOS¶
A portable layer in port/ implements the part of the Win32 API that MFC
uses over POSIX, so the libraries also build for Linux and macOS with
the system's own clang:
make TARGET=x86_64-linux-gnu STDLIB= # Linux (glibc, libstdc++)
make TARGET=arm64-apple-macos11 STDLIB= # macOS
Without BIN, the build uses llvm-ar when it is on the path and the
system's ar otherwise.
This adds libwinport.a, which programs link after the MFC library:
clang++ -std=c++17 -Ipath/to/mfc/port/include -Ipath/to/mfc/include app.cpp \
-Lpath/to/build/x86_64-linux-gnu -lmfc -lwinport -ldl -lpthread -o app
On macOS the system libraries are -framework Cocoa -lpthread instead
of -ldl -lpthread.
make install (to /usr/local, or PREFIX=dir; DESTDIR works too)
puts the headers in include/libmfc (the portable layer's in
include/libmfc/winport), the static libraries in lib, the shared
ones in lib/libmfc-shared, and res2cpp.py in share/libmfc. It also
installs pkg-config files, libmfc and libmfcu (Unicode) for the
static libraries and libmfc-shared and libmfcu-shared for the shared
ones, and a CMake package, libmfc. Both find the install from where
they are, so the tree can be moved:
python3 "$(pkg-config --variable=res2cpp libmfc)" app.rc -o app-res.cpp
clang++ app.cpp app-res.cpp $(pkg-config --cflags --libs libmfc) -o app
find_package(libmfc REQUIRED)
add_executable(app WIN32 app.cpp)
target_link_libraries(app PRIVATE libmfc::mfc) # or mfcu, mfc_shared, mfcu_shared
libmfc_add_resources(app app.rc)
A program may define its own WinMain, as on Windows (declared with C
names in winbase.h); otherwise the library's runs AfxWinMain.
A program's resources go in as C++: port/tools/res2cpp.py compiles the
.rc file with llvm-rc and writes the result as a source file that
registers it before the program's constructors run (it needs Python 3,
llvm-rc and clang):
MFC's include directory is searched after any given with -I.
It is a work in progress. So far the non-window classes, automation, the
registry (kept in ~/.config/libmfc/registry.reg), resources, sockets
(with WSAAsyncSelect), ODBC through the system's driver manager
(unixODBC or iODBC, loaded when first used; WINPORT_ODBC names its
library when it is elsewhere),
WinInet's HTTP, HTTPS, FTP and gopher, and COM, both within a process
(in-process servers in a shared library included) and between
processes (local servers COM starts, with IDispatch, OLE documents'
interfaces, type information and monikers crossing), work, and so does the window manager: window
classes and windows, messages and the message loop, timers, hooks,
focus, painting, and drawing in software with device contexts, bitmaps,
DIBs, regions, fills and blits, lines, curves, shapes and paths, and
text. Windows show on Wayland, on X11 or with Cocoa on macOS (Mac OS X
10.4 and later, PowerPC and Intel); WINPORT_BACKEND picks one
(wayland, x11, cocoa, or headless to keep windows in memory, as
the tests do). A window draws its own frame, the caption's icon
included, so on Wayland it asks the compositor for client-side
decorations (xdg-decoration); its icon goes to the taskbar and the
window switcher (_NET_WM_ICON on X11, xdg-toplevel-icon on Wayland,
the Dock on macOS). Wayland, X11 and xkbcommon are loaded when a program
starts, so it runs without them. Text copied and pasted through the
clipboard goes to and from other programs.
Printing and print preview work too. The printers are the system's CUPS
queues and "Save as PDF"; a printer DC draws each page as a picture at
the printer's resolution (300 dots an inch unless the DEVMODE asks for
another), and the job becomes a PDF file that goes to CUPS's lp, to the
file DOCINFO names, or (for "Save as PDF" with no file named) to the
document's name in ~/Documents. PrintDlg and PageSetupDlg show their
dialogs, with hooks and the usual control IDs from dlgs.h, or return
the default printer. WINPORT_PRINTERS=pdf leaves CUPS out.
Anonymous pipes (CreatePipe, PeekNamedPipe) give a child started
with STARTF_USESTDHANDLES its standard input and output. Serial ports
work over termios: COM1 is the device WINPORT_COM1 names, or else
/dev/ttyS0 on Linux and the first /dev/cu.* device on macOS, and a
device's own path (/dev/ttyUSB0) opens as a port too. Its DCB,
COMMTIMEOUTS, modem lines and WaitCommEvent work as on Windows, and
reads, writes and event waits on a port opened with
FILE_FLAG_OVERLAPPED run in the background until GetOverlappedResult
or the event says they are done.
Sound goes through ALSA on Linux (libasound, loaded when first used;
WINPORT_AUDIO_DEVICE names the device) and through audio queues on
macOS. waveOut and waveIn take any format the built-in ACM driver
reads (PCM of 8 to 32 bits and float, A-law, mu-law and IMA ADPCM, at
any rate and channels) and convert it for the device, with callbacks,
loops, pause, positions and volume. The ACM itself enumerates, suggests
and converts those formats. mmio reads and writes RIFF files on disk
and in memory; PlaySound plays WAVE files, resources and images; and
timeSetEvent timers run on their own threads. WINPORT_AUDIO=null
chooses a loopback device that keeps time like a sound card and records
what was played. Beep plays its tone the same way.
GetEnvironmentStrings, GetUserName (from the password database) and
SHGetFolderPath work: CSIDL_APPDATA and the other folders are the
XDG folders on Linux (XDG_CONFIG_HOME, XDG_DATA_HOME and the
user-dirs.dirs names such as Documents) and the usual folders under
~/Library on macOS, and CSIDL_PROFILE is the home folder.
SendInput, mouse_event and keybd_event feed the window manager's
input as a real mouse and keyboard would, and mouse messages go to the
window under the pointer, passing through controls that answer
WM_NCHITTEST with HTTRANSPARENT (such as group boxes).
Kernel objects go further than events, mutexes and semaphores: named
ones, shared with the user's other processes through POSIX shared memory
(a mutex whose owner's process ends is abandoned to the next waiter;
waits in other processes look again every few milliseconds), waitable
timers (named ones within the process), APCs and alertable waits
(QueueUserAPC, SleepEx), I/O completion ports (packets posted, and
the results of overlapped reads and writes on a file associated with
one), and file mappings over mmap (a named mapping without a file is
POSIX shared memory, which other processes open by name). Services work
too: the service control manager keeps them under
HKLM\SYSTEM\CurrentControlSet\Services, StartService runs the
program, and its dispatcher takes ControlService's controls over a
local socket; ReportEvent writes to the system log. The registry's
file is shared: each change is written at once, under a lock, and a
program reads the file again when another has changed it. The file is
plain text, much as regedit exports it ("name"="text",
"name"=dword:1), so a person can edit it. The configuration directory
($XDG_CONFIG_HOME/libmfc, or ~/.config/libmfc) holds it and the
.ini files.
The look can be changed there. The system colors come from
HKEY_CURRENT_USER\Control Panel\Colors when a program starts, by
Windows' names for them, and the caption shades from each title color to
its gradient color when GradientCaptions is set:
[HKEY_CURRENT_USER\Control Panel\Colors]
"ActiveTitle"="0 84 147"
"GradientActiveTitle"="58 166 240"
"ButtonFace"="212 208 200"
[HKEY_CURRENT_USER\Control Panel\Desktop]
"GradientCaptions"=dword:00000001
The other names are Scrollbar, Background, InactiveTitle,
GradientInactiveTitle, Menu, MenuBar, MenuText, MenuHilight,
Window, WindowFrame, WindowText, TitleText, InactiveTitleText,
ActiveBorder, InactiveBorder, AppWorkspace, Hilight,
HilightText, ButtonShadow, ButtonHilight, ButtonDkShadow,
ButtonLight, ButtonText, ButtonAlternateFace, GrayText,
InfoText, InfoWindow and HotTrackingColor. SetSysColors and
SPI_SETGRADIENTCAPTIONS change them while the program runs (bit 0x10
of UserPreferencesMask, as on Windows, also turns the gradient on).
Sizes and fonts come from HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics:
BorderWidth, CaptionWidth, CaptionHeight, SmCaptionWidth,
SmCaptionHeight, MenuWidth, MenuHeight, ScrollWidth and
ScrollHeight in pixels (or, as Windows keeps them, negative twips:
"-270" is 18 pixels), and CaptionFont, SmCaptionFont, MenuFont,
StatusFont, MessageFont and IconFont as "face,points" with
,bold or ,italic after it (or a LOGFONTW as Windows writes it):
[HKEY_CURRENT_USER\Control Panel\Desktop\WindowMetrics]
"CaptionHeight"="24"
"CaptionFont"="DejaVu Sans,9,bold"
"MenuFont"="DejaVu Sans,9"
SPI_SETNONCLIENTMETRICS changes them while the program runs, and
windows that are open take the new frame; with SPIF_UPDATEINIFILE it
saves them there too, as SPI_SETGRADIENTCAPTIONS does the gradient.
Each program watches the registry file (with inotify on Linux, kqueue on
macOS), so saving it in an editor, or another program changing these
keys, restyles the programs already running: what changed is applied
as it would be on Windows, colors with WM_SYSCOLORCHANGE and sizes and
fonts with WM_SETTINGCHANGE and a new frame. A color a program set
itself with SetSysColors stays until the file changes that color.
GDI+ is there as far as images go (CImage uses it): bitmaps in the
usual pixel formats, locking their bits, and BMP, PNG, JPEG and GIF
files and streams, read with stb_image
and PNG and JPEG written with stb_image_write (public domain or MIT, in
port/src/third_party/), BMP and GIF by hand. A GIF is written as one
frame: an indexed bitmap with its own palette, and a true-color one with
its own colors when it has 256 or fewer, else through a color cube
(GDI+ takes every true-color image through its halftone palette);
pixels under half alpha become the transparent color. CryptoAPI has the base and
enhanced providers' hashes (MD4, MD5, SHA-1, SHA-256, SHA-384, SHA-512
and HMAC), RC4 and AES keys (derived, imported or random),
CryptGenRandom, and RSA: key pairs generated or imported (1024 bits
unless asked, 384 to 16384), PKCS #1 v1.5 and OAEP encryption, PKCS #1
v1.5 signatures, and PUBLICKEYBLOB, PRIVATEKEYBLOB and SIMPLEBLOB
blobs, in CryptoAPI's byte order. Key containers are directories under
crypto/user/ in the configuration directory (crypto/machine/ for
CRYPT_MACHINE_KEYSET), one file for each pair, readable by the owner
only and not encrypted; opening one that is not there fails with
NTE_BAD_KEYSET until CRYPT_NEWKEYSET makes it. A private key blob
exports only in plain, not wrapped in a session key. shlwapi's path
and string functions, access control lists and SDDL work as well.
The shell namespace is the file system: the desktop is the root /,
an item ID list holds one item for each component of a path, and shell
folders (SHGetDesktopFolder, IShellFolder) list, parse, compare and
rename what is in them. There are no shortcuts (SFGAO_LINK), since
symbolic links need none. SHBrowseForFolder shows a tree of the
folders below its root and answers the BFFM_ messages. There are no
visual styles: the controls draw the classic look, as Windows does with
styles turned off, so OpenThemeData opens nothing and IsThemeActive
is false. There is one monitor, the screen. There is no OpenGL: no
pixel format can be chosen and wglCreateContext fails.
Layered windows show with their transparency: SetLayeredWindowAttributes
with a color key and a constant alpha, and UpdateLayeredWindow (and
UpdateLayeredWindowIndirect) with a picture's own premultiplied alpha
from a 32-bit DIB section, the constant alpha over it, or a color key.
As on Windows, the mouse goes through a layered window where it is fully
transparent, and everywhere with WS_EX_TRANSPARENT; a layered window
shows nothing until it has attributes or a picture; and once
SetLayeredWindowAttributes is called, UpdateLayeredWindow fails until
WS_EX_LAYERED is cleared and set again. A window region from
SetWindowRgn cuts a top-level window's shape on the screen the same
way. On X11 a translucent window gets a 32-bit visual when a compositing
manager runs; without one, its color key and region become a shape
(SHAPE extension) and its alpha is not shown. Its input shape follows
the transparent pixels either way. On Wayland it is an ARGB buffer with
an input region, and on macOS a window that is not opaque. The desktop's
DC (GetDC(NULL)) reads the screen with translucent windows blended.
A regular DLL builds as a shared library (-shared, exporting
DllMain and the .def file's names; the program links with
-rdynamic on Linux, and the library with -undefined dynamic_lookup
on macOS), and LoadLibrary calls its DllMain.
The shared libraries build too (make all; make static leaves them
out). They go in build/<target>/shared under the static libraries'
names, libmfc.so, libmfcu.so and libwinport.so (.dylib on
macOS), so a program built with _AFXDLL picks them with that
directory first, and links libmfcs.a (libmfcus.a) for its own part:
clang++ -std=c++17 -D_AFXDLL -Ipath/to/mfc/port/include -Ipath/to/mfc/include app.cpp \
-Lpath/to/build/x86_64-linux-gnu/shared -Lpath/to/build/x86_64-linux-gnu \
-lmfcs -lmfc -lwinport -ldl -lpthread -Wl,-rpath,path/to/build/x86_64-linux-gnu/shared -o app
Extension DLLs (_AFXEXT) and regular DLLs that share the library work
as on Windows: the program's startup calls the DllMain of each
library it links with, and a regular DLL keeps a module state of its
own.
The common controls are all there: besides the bars, list and tree views, tabs and the rest, the rebar, pager, SysLink, IP address, ComboBoxEx, animation (uncompressed and RLE8 AVI clips), month calendar and date and time picker.
HTTPS uses OpenSSL (libssl 3 or 1.1, loaded when first used;
WINPORT_LIBSSL names it when it is elsewhere), and on macOS the
system's Secure Transport. The server's certificate is checked as
WinInet checks it, and INTERNET_OPTION_SECURITY_FLAGS
(SECURITY_FLAG_IGNORE_UNKNOWN_CA and the others) lets a problem with
it go. PlgBlt draws through a parallelogram (and a mask) in software.
There is no WinHelp viewer: WinHelp (and so MFC's Help commands)
opens a document next to the program's .hlp file instead, of the same
name as .html, .htm, .pdf or .txt (or a folder of that name with
an index.html), with the desktop's opener, or with the command that
WINPORT_HELP names. A help context is the HTML page's anchor
(app.html#131072). The internet security manager has no zone settings:
local files and res: are the local machine, a share or a host without
a dot the intranet, the rest the internet, and SetZoneMapping adds
mappings for the process.
The functions not written yet are
listed in port/src/stubs.txt and fail with ERROR_CALL_NOT_IMPLEMENTED;
WINPORT_DEBUG=1 names each one the first time a program calls it.
Text uses the TrueType and OpenType fonts installed on the system,
read with stb_truetype (public domain
or MIT, in port/src/third_party/); Windows names such as MS Sans Serif,
Times New Roman and Courier New map to similar installed families
(Arial, Liberation, DejaVu, Helvetica and so on). WINPORT_FONTS lists
the folders to search instead of the system's, separated by colons; set
to builtin, text uses only the built-in fallback, the public domain
X11 6x13 bitmap font (port/tools/gen-builtin-font.py makes
port/src/font_builtin.inc from it). Symbol and Wingdings are symbol
fonts as on Windows: their A text is read a byte at a time, and when
the font is not installed each character is drawn as its Unicode
counterpart (the Adobe Symbol mapping, and for Wingdings the characters
Unicode encodes, such as U+2713 for the check mark), from the stand-in
family or a symbol font such as Symbola, Noto Sans Symbols or DejaVu
Sans. A Wingdings character with no clear counterpart draws as its byte.
The ANSI code page there is UTF-8, WCHAR is the system's 32-bit
wchar_t, and long is 64 bits on 64-bit systems while LONG and
DWORD stay 32 bits. Code that passes a long* where the API takes a
LONG* needs LONG; in dispatch maps long remains the type of
VT_I4, as MFC documents.
The shared library¶
A program built with _AFXDLL uses the library in mfc.dll (mfcu.dll
for Unicode), which goes next to the program. afx.h then names
mfcdll (the import library) and mfcs (mfcudll and mfcus), the
latter with the few pieces each module keeps for itself, such as
WinMain:
clang++ --config=winxp.cfg -D_AFXDLL -Ipath/to/mfc/include app.cpp app-res.o \
-Lpath/to/build/i586-pc-windows5.1-gnu -mwindows -o app.exe
The DLL uses no C runtime DLL of its own choosing: it is built with the
same C library as the program (msvcrt.dll, or a static picolibc in
each module, whose malloc takes its blocks from the process heap), so
memory from new or malloc in one module can be freed in another.
With MinGW and libstdc++, link without -static, so that libstdc++ and
libgcc are DLLs too: only then does an exception thrown in one module
reach a catch in another.
An extension DLL is built with _AFXDLL and _AFXEXT and shares the
program's mfc.dll: its classes, marked AFX_EXT_CLASS (functions
AFX_EXT_API), are part of the program, and its resources are found
after the program's own. Its DllMain registers it (AppWizard's
#include <afxdllx.h> before it is accepted and does nothing more):
static AFX_EXTENSION_MODULE extDLL = {NULL, NULL};
extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID) {
if (dwReason == DLL_PROCESS_ATTACH) {
if (!AfxInitExtensionModule(extDLL, hInstance)) return 0;
new CDynLinkLibrary(extDLL);
} else if (dwReason == DLL_PROCESS_DETACH) {
AfxTermExtensionModule(extDLL);
}
return 1;
}