pythoncmakepybind11

Cannot open python312.lib for compiling a basic CMakeLists project on windows for pybind11


I am trying to get the example case to compile with CMake on windows but there is a constant linker error when I try to use CMake. The following is the CMakeLists.txt

cmake_minimum_required(VERSION 3.28)

project(example LANGUAGES CXX)

find_package(pybind11 REQUIRED)

pybind11_add_module(example example.cpp)

This is example.cpp

#include <pybind11/pybind11.h>

int add(int i, int j) {
    return i + j;
}

PYBIND11_MODULE(example, m) {
    m.doc() = "pybind11 example plugin";
    m.def("add", &add, "A function that adds two numbers");
}

The error when running on Windows is LINK : fatal error LNK1104: cannot open file 'python312.lib' [C:\Users\UserName\Documents\Code\build\example.vcxproj]

I manually added the python lib path as target_include_directory to try and fix the issue, and pybind11 was also installed as pip install "pybind11[global]" but this error didn't occur on Linux. I haven't tried including pybind11 as a git sub directory because it wouldn't work with the project I'm trying to port over to windows.


Solution

  • Depending on how you installed Python and pybind11 on your windows setup, you probably don't have the pybind11Config.cmake file on the path.

    One thing you can do is

    1. Find the package cmake config file with
    import pybind11
    print(pybind11.__path__)
    # will print something like --> ['C:\\Users\\username\\AppData\\Local\\anaconda3\\Lib\\site-packages\\pybind11']
    
    1. Specify pybind's cmake file path in the CMakeLists.txt file so that it becomes
    cmake_minimum_required(VERSION 3.28)
    
    project(example LANGUAGES CXX)
    
    find_package(pybind11 REQUIRED PATHS  C:\\Users\\username\\AppData\\Local\\anaconda3\\Lib\\site-packages\\pybind11\\share\\cmake\\pybind11\\)
    
    pybind11_add_module(example example.cpp)
    

    Watch out, notice that the path I set for the package is not exactly the one returned by the python code, I had to look where pybind11Config.cmake was located.