Ray's Knowledge Base

Build PCRE2 as a static 8-bit library with JIT through CPM

RecipeVerified 28 Sep 2026Holds anywhere
Recipe. When to use it, the steps, and what showed that they work.

When to use#

A CMake project that fetches dependencies with CPM needs a regex engine and should link PCRE2 statically, without the 16- and 32-bit libraries, pcre2grep or tests.

Steps#

  1. Pin a release tag (list them with git ls-remote --tags https://github.com/PCRE2Project/pcre2; tags are pcre2-10.NN):

    cpmaddpackage(
      NAME pcre2
      GITHUB_REPOSITORY PCRE2Project/pcre2
      VERSION 10.48
      GIT_TAG pcre2-10.48
      OPTIONS
        "BUILD_SHARED_LIBS OFF" "BUILD_STATIC_LIBS ON" "PCRE2_STATIC_PIC ON"
        "PCRE2_BUILD_PCRE2_8 ON" "PCRE2_BUILD_PCRE2_16 OFF" "PCRE2_BUILD_PCRE2_32 OFF"
        "PCRE2_SUPPORT_JIT ON" "PCRE2_SUPPORT_UNICODE ON"
        "PCRE2_BUILD_PCRE2GREP OFF" "PCRE2_BUILD_TESTS OFF"
        "PCRE2_SUPPORT_LIBBZ2 OFF" "PCRE2_SUPPORT_LIBZ OFF"
        "PCRE2_SUPPORT_LIBEDIT OFF" "PCRE2_SUPPORT_LIBREADLINE OFF")
    
  2. Link the static target and set the two definitions every translation unit that includes pcre2.h needs:

    target_link_libraries(mylib PRIVATE $<BUILD_INTERFACE:pcre2-8-static>)
    target_compile_definitions(mylib PRIVATE PCRE2_CODE_UNIT_WIDTH=8 PCRE2_STATIC)
    

    The target is pcre2-8-static (10.48 also defines the alias pcre2-8).

  3. Check that JIT is on: build/.../_deps/pcre2-build/src/config.h holds #define SUPPORT_JIT 1.

  4. In code, call pcre2_jit_compile(code, PCRE2_JIT_COMPLETE) and ignore its failure: without JIT, pcre2_match uses the interpreter with the same results. Keep a match context with pcre2_set_match_limit/pcre2_set_depth_limit and a JIT stack (pcre2_jit_stack_create, pcre2_jit_stack_assign) per thread, and treat PCRE2_ERROR_MATCHLIMIT/DEPTHLIMIT as "no answer" rather than an error.

Evidence#

  • dftracer-utils cmake/modules/Dependencies.cmake need_pcre2() (2026-09-28, macOS arm64, Apple clang): the configure summary listed only the 8-bit library, config.h had SUPPORT_JIT 1, the library built with the project's strict warnings unaffected, and a pattern such as ^(a|aa)+$ on 10,000 a characters returned without hanging in 100 repeated runs.