Compile and add an object file from a binary with CMake

后端 未结 2 1905
一生所求
一生所求 2020-12-24 14:48

I am writing an Excel file builder in C++.

I have everything I need working, but I still rely on an external empty .xlsx file which I unzip, iterate through, and add

相关标签:
2条回答
  • 2020-12-24 15:04

    To link the object file into the exectuable, add it to the list of source files in add_executable() instead of trying to add it to target_link_libraries().

    For generating the object file in the first place, see add_custom_command(). In this case, you will want to use its form which specifies an OUTPUT parameter.

    0 讨论(0)
  • 2020-12-24 15:25

    In the end, this is how I did it.

    add_custom_command(OUTPUT template.o
          COMMAND cd ${CMAKE_CURRENT_SOURCE_DIR}/files && ld -r -b binary -o ${CMAKE_CURRENT_BINARY_DIR}/template.o template.xlsx
          COMMAND objcopy --rename-section .data=.rodata,alloc,load,readonly,data,contents ${CMAKE_CURRENT_BINARY_DIR}/template.o ${CMAKE_CURRENT_BINARY_DIR}/template.o)
    

    The cd commands are there because ld sets the names of the automatically declared variables to something depending on the full path passed to the input file. So if the input file was /home/user/project/files/template.xlsx, the variable would be something like _binary_home_user_project_files_template_xlsx_start. Not cool for portable compilation.

    add_library(template
            STATIC
            template.o)
    

    tells the linker to compile the object file into the binary. This also adds a target called template.

    Then

    SET_SOURCE_FILES_PROPERTIES(
      template.o
      PROPERTIES
      EXTERNAL_OBJECT true
      GENERATED true
      )
    

    to tell CMake not to compile the file, which is generated at build time.

    SET_TARGET_PROPERTIES(
      template
      PROPERTIES
      LINKER_LANGUAGE C 
      )
    

    Or else we get an error message, because CMake can't figure out from the ".o"-suffix that it is a C linker we need.

    And then in my target_link_libraries step, I simply added template as a target.

    target_link_libraries (excelbuilder
                ${MINIZIP_LIB_NAME}
                ${TINYXML_LIBRARIES}
                ${MYSQLCONNECTORCPP_LIBRARY}
                ${Boost_LIBRARIES}
                template
                )
    
    0 讨论(0)
提交回复
热议问题