EOSIO / eosio.cdt

EOSIO.CDT (Contract Development Toolkit) is a suite of tools used to build EOSIO contracts
http://eosio.github.io/eosio.cdt
MIT License
512 stars 288 forks source link

How to link external libraries with cmake? #1235

Open nidhaloff opened 2 years ago

nidhaloff commented 2 years ago

I want to link an external library to my contract. I did not find examples on how to do this. All examples are very basic and do not include external libs.

I know that there is a macro add_contract, but is there also a macro for target_link_contracts or something like this because target_link_libraries is not working in this case.

Here is my cmake config

cmake_minimum_required(VERSION 3.16)

project(proj VERSION 1.0.0)

# include external lib
include(FetchContent)
FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git GIT_TAG f4622efcb59d84071ae11404ae61bd821c1c344b) # the commit hash for 1.6.2
FetchContent_MakeAvailable(cpr)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)

find_package(eosio.cdt)
add_contract( ${PROJECT_NAME} ${PROJECT_NAME} src/main.cpp)

target_link_libraries(${PROJECT_NAME} cpr::cpr)   # this line is not working. I can't link the cpr lib why?

This is the error I receive

CMake Error at CMakeLists.txt:28 (target_link_libraries):
  Cannot specify link libraries for target "proj" which is not built
  by this project.
praphael commented 2 years ago

Everything needs to be compiled with eosio-cpp, as the target is Web Assembly. Trying to link a native library definitely will not work. If you have the source code to the library, you can try to include it as part of the compile and this may work, depending on what header files it tries to include. If it is a large library, this may present problems with the smart contract size. Typically the generated WASM should be < 1 MB.