Technical Article

Static Linking jbig2enc Into Free Pascal Without a DLL

Link a set of MSVC-compiled C objects into a 64-bit Free Pascal program, chase down every undefined symbol one by one, and the reward for resolving the last of them is Internal error 200603061: no symbol, no section, no object file in the message. The cause is how the Free Pascal internal linker folds pick-any COMDAT sections, and the cure lives in the object files themselves, because no compiler or linker switch reaches it

The COFF constructs Free Pascal will not link

PDFlibPas ships its external JBIG2 encoder, jbig2enc built on the leptonica image library, as prebuilt Win64 object files linked straight into the executable. For Free Pascal that object set is compiled with MSVC and then rewritten before any Pascal code sees it, because the Free Pascal COFF reader rejects or mishandles four things MSVC emits as a matter of routine. All four are properties of the object file, which is the whole point of this article:

Construct in the objectWhere MSVC emits itWhat Free Pascal reportsObjConv switch
Weak external symbols (IMAGE_SYM_CLASS_WEAK_EXTERNAL)Every template or inline instantiationUnsupported COFF symbol type 105-xw
Associative COMDAT sectionsThe .pdata and .xdata unwind recordsAssociative or exact match COMDAT sections are not yet supported-xc
Pick-any COMDAT sectionsEvery string literal, every inline or template instantiationInternal error 200603061-xc
IMAGE_SYM_CLASS_NULL symbols such as _fltusedFloating-point support markersUnsupported COFF symbol type 0-xn

The routes around the internal linker all end badly, and the walkthrough of the JBIG2 encoder backends and the Free Pascal linker routes covers them in detail. In short: the binutils ld bundled with Free Pascal crashes inside --gc-sections, a flag Free Pascal always passes for an external link on Win64; binutils 2.44 cannot process the Free Pascal link script at all; and rebuilding the C++ side with clang still produces weak externals, because template instantiation emits them by construction. Every one of those attempts goes through a compiler or a linker. Neither can change what an object file already contains, so the fix has to be a post-processing step on the objects

Why internal error 200603061 names nothing

The Free Pascal internal linker implements pick-any COMDAT only halfway. It folds duplicate definitions exactly as the format intends. But TExeOutput.RemoveUnreferencedSections, the pass that marks sections as used, follows exesymbol to the winning copy of a folded definition, while TCoffexeoutput.DoRelocationFixup reads objreloc.symbol.objsection directly. When a used section references a symbol that its own object defines in a copy that lost the fold, the two passes are looking at two different sections, and the fixup pass gives up with Internal error 200603061

PDFlibPas static linking hits internal error 200603061 when the Free Pascal linker folds duplicate pick-any COMDAT sections: RemoveUnreferencedSections resolves a symbol through exesymbol to the winning copy while DoRelocationFixup reads objreloc.symbol.objsection directly, so the two passes aim at different sections and the link stops without naming a symbol, section, file or phase
When a used section references a symbol whose losing COMDAT copy the fold discarded, the marking pass and the relocation pass read different sections, and Free Pascal stops with an internal error that names nothing

Put the three messages side by side and the asymmetry is striking. Type 105 tells you it is a weak external. The associative COMDAT message names the construct and even the offending symbol, .rdata in the clang-built objects. Internal error 200603061 is a bare number. It is also the common case rather than an edge case: across the 186 objects in this encoder set the linker performed 2656 folds. Compiling with /Gy- keeps ordinary functions out of per-function COMDAT sections, which looks like the right knob, yet string literals and template instantiations stay in pick-any COMDAT regardless, and those are what trigger the mismatch

The last CRT stub always looks guilty

The Free Pascal linker only reaches the relocation fixup pass after every symbol has resolved. While anything is still undefined, the run ends early with Undefined symbol, and the COMDAT problem never gets its turn. We walked straight into this while supplying Pascal bodies for the C runtime names the objects import, one batch at a time. Each time the list of undefined symbols reached zero, the link died with 200603061, so it always looked as if the most recent stub had broken the build. At one point it looked like a threshold, something around a hundred stubs. It was neither. The failure was latent from the first object and only became reachable once symbol resolution succeeded

The general rule is worth keeping: when a linker swaps one complaint for a different one right after you fixed something unrelated, check whether you moved it to its next phase before you hunt for a regression. Two build choices also shrink the stub list, and I would make both for any C library linked this way:

  • leptonica is compiled with HAVE_LIBJPEG, HAVE_LIBTIFF, HAVE_LIBPNG and HAVE_LIBZ set to 0, so it builds its own stub versions of the codec and file I/O paths, which the in-memory encode path never touches
  • _NO_CRT_STDIO_INLINE stops the UCRT headers from inlining the printf and scanf family into every translation unit, which would collide with Pascal exports of the same names and drag in the __stdio_common_* entry points behind them

Fewer imported names means fewer Pascal bodies that have to match a C calling convention by hand, and every one of those bodies is a place to get an argument type wrong

One ObjConv pass over every object

The whole correction is a single command run over each compiled object: ObjConv -fcoff64 -xw -xc -xn -np:__imp_:pdflibimp_. ObjConv reads COFF and writes COFF, so the output drops straight into a {$L} directive. The -xw, -xc and -xn options are not part of a stock ObjConv; they were added to the copy that builds this object set, so expect to carry that change yourself if you reproduce the pipeline for another library

-xc does the heavy lifting. It demotes every COMDAT section to a plain section and makes the symbols it defines static, which removes the failure by removing the decision: with no COMDAT sections left there is no folding, no winning copy for one pass to follow and the other to miss, and the associative unwind sections stop being associative. The cost is that copies which could have merged now each survive in the executable, such as string literals and inline or template instantiations that several objects share. That is the right trade. Duplicate copies cost a predictable amount of space, while a patch to the Free Pascal linker would have to follow every compiler version a project builds with

PDFlibPas builds its statically linked jbig2enc backend for Free Pascal by running ObjConv -fcoff64 -xw -xc -xn -np:__imp_:pdflibimp_ over each MSVC object, demoting COMDAT sections to plain sections, resolving weak externals, normalizing IMAGE_SYM_CLASS_NULL symbols and renaming import cells, then linking the plain COFF64 objects from Lib\thirdparty\Win64f into the executable with no DLL to deploy
One post-processing pass with ObjConv removes the constructs Free Pascal cannot link, so the same PDFlibJBIG2EncC unit that serves Delphi and C++Builder now lands the encoder inside the Free Pascal executable with no file to deploy

The -np:__imp_:pdflibimp_ rename handles a separate collision. MSVC calls imported Win32 APIs through pointer cells named __imp_*, and Free Pascal reserves that prefix for its own import machinery; defining one of those names in Pascal trips the same internal error 200603061. After the rename the cells are ordinary data symbols that the Pascal side can publish and fill in. The objects are compiled with the static-link flag set, /GS- /Gs999999 /Gy- /Zl plus /GR- /EHs-c- for the C++ units, and land in Lib\thirdparty\Win64f. Delphi and C++Builder link a separate clang-built set from Lib\thirdparty\Win64x, which their linker already accepts, so the Free Pascal pipeline never touches that set

Publishing C symbols from the Pascal side

A C object binds to its imports by symbol name, and Free Pascal needs that name spelled out on the Pascal routine with a public name clause. Delphi uses the routine name as the symbol name and needs no clause, so a unit that serves both compilers wraps the clause in {$IFDEF FPC}. The PDFlibJBIG2EncC unit declares its math and string helpers exactly that way, for example Function htonl(hostlong: Cardinal): Cardinal; Cdecl; {$IFDEF FPC}Public Name 'htonl';{$ENDIF}

The trap is the external declaration. Pointing a routine at msvcrt.dll creates an import, and an import is not a definition that a linked object can bind to. The Pascal body has to exist and forward the call:

// An external declaration creates an import only. No linked object can
// bind to it.
function crt_memcmp(Buf1, Buf2: Pointer; Count: NativeUInt): Integer; cdecl;
  external 'msvcrt.dll' name 'memcmp';

// A Pascal body published under the exact C symbol name is what the
// object set actually binds to.
function jbig2_memcmp(Buf1, Buf2: Pointer; Count: NativeUInt): Integer; cdecl;
  public name 'memcmp';
begin
  Result := crt_memcmp(Buf1, Buf2, Count);
end;
One PDFlibPas unit serves Delphi, C++Builder and Free Pascal because an external declaration only creates an import while a Pascal body published under public name 'memcmp' is the definition the object set binds to, and varargs entry points like sprintf tail-jump through SPrintfTarget with the caller's frame untouched instead of forwarding arguments
An external declaration creates an import nobody can bind to, while a Pascal body with a public name clause is a real definition, and varargs routines dodge forwarding entirely by tail-jumping with the caller's frame untouched

Variadic functions break that pattern, since a Pascal routine cannot forward its own varargs to another varargs callee. Stop being a wrapper instead. Export a frameless assembler routine under the C name and jump to the real implementation with the argument registers and the stack exactly as the caller left them. The same trick covers snprintf and vsnprintf, with one extra wrinkle: msvcrt exports them only with a leading underscore, as _snprintf and _vsnprintf, and the plain names exist in the UCRT alone

function crt_sprintf(Buffer: PAnsiChar; Fmt: PAnsiChar): Integer; cdecl; varargs;
  external 'msvcrt.dll' name 'sprintf';

var
  SPrintfTarget: Pointer = @crt_sprintf;

// Varargs cannot be forwarded from a Pascal wrapper, so the exported
// symbol tail-jumps with the frame left exactly as the caller set it up.
procedure jbig2_sprintf; assembler; nostackframe;
  public name 'sprintf';
asm
  jmp qword ptr [rip + SPrintfTarget]
end;

Exported variables have two quirks of their own, and both surface as the same internal error. A variable published with public name trips it, so the renamed import cells are declared with cvar; public under their final C spelling. A static initializer that takes the address of an imported routine for one of those cells trips it as well, so the cells start as nil and get their addresses in an initialization section:

uses
  Windows;

var
  // ObjConv renamed __imp_DeleteFileA to pdflibimp_DeleteFileA; cvar keeps
  // the C spelling without a public name clause
  pdflibimp_DeleteFileA: Pointer = nil; cvar; public;

function ResolveApi(const Module, Symbol: PAnsiChar): Pointer;
var
  Handle: HMODULE;
begin
  Result := nil;
  Handle := GetModuleHandleA(Module);
  if Handle = 0 then
    Handle := LoadLibraryA(Module);
  if Handle <> 0 then
    Result := GetProcAddress(Handle, Symbol);
end;

initialization
  pdflibimp_DeleteFileA := ResolveApi('kernel32.dll', 'DeleteFileA');
end.

What a Lazarus project actually writes

From the application side, the static backend comes down to one unit name in the uses clause and no file to deploy. On Win64 under Free Pascal, PDFlibJBIG2EncC pulls in its own export units and links the Win64f object set, then registers the encoder from its initialization section through RegisterJBIG2EncoderBackend. Callers request it through options bit PDF_JBIG2_OPTION_EXTERNAL_ENCODER, which has the value 4, or through the UseExternalEncoder argument of the extended entry points such as AddImageJBIG2FromStreamEx:

uses
  Classes, SysUtils,
  PDFlibrary,
  PDFlibJBIG2EncC;   // same unit for Delphi, C++Builder and Free Pascal

var
  Pdf: TPDFlib;
  Scan: TStream;
  ImageId: Integer;
begin
  Pdf := TPDFlib.Create;
  try
    Pdf.NewDocument;            // creates and selects page 1
    // The stream is loaded as a bitmap and reduced to 1 bit per pixel
    Scan := TFileStream.Create('scan-page-1.bmp', fmOpenRead);
    try
      // Interpolate, SymbolExtract, UseExternalEncoder, SkipBlackDots,
      // BlackDotSize, LossyLevel
      ImageId := Pdf.AddImageJBIG2FromStreamEx(Scan, 0, 1, 1, 0, 0, 0);
    finally
      Scan.Free;
    end;
    if ImageId = 0 then
      raise Exception.Create('JBIG2 encoding failed');
    Pdf.SaveToFile('archive.pdf');
  finally
    Pdf.Free;
  end;
end;

The object set covers Win64 only. On other Free Pascal targets the external encode entry point reports failure and the native Pascal MMR encoder produces the JBIG2 stream, and the same happens in any build that leaves PDFlibJBIG2EncC out of the uses clause. In both cases AddImageJBIG2FromStreamEx still returns a valid image ID, just with a larger stream

The Pascal side also hands the encoder bit-inverted scanlines, because a Windows DIB and leptonica disagree on which bit value means black; the JBIG2 encoder backend article covers that polarity flip and the render comparison that confirms both encoders produce identical pages

When a DLL is still the right shape

A DLL earns its place when the boundary really is dynamic, which is the case the DLL, ActiveX and dylib integration surfaces are built for. As a workaround for a COFF reader it is the weaker choice: it adds a file to every installer, a search path to every deployment and a version-skew failure that a statically linked encoder simply cannot have. Encoder choice is also only half of the size story, since how the bilevel image is produced upstream decides as much as the codec does, and region-based monochrome rendering in Delphi covers that half. Compiler coverage, the per-toolchain object sets and the supported targets for the encoder are listed on the losLab PDF Developer Library product page