Vova Polischuck Vova Polischuck - 2 months ago 18
C++ Question

Linking static library (".a" extension) to CMake file

I have tried to link my libencode_linux_x86_64.a static library with CMake file. My initial CMake file is:

cmake_minimum_required(VERSION 3.6)
project(Coder)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp coder.cpp coder.h)
add_executable(Coder ${SOURCE_FILES})


It were different problems I had. For example, i added the following properties to my goal:

cmake_minimum_required(VERSION 3.6)
project(Coder)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp coder.cpp coder.h)
add_executable(Coder ${SOURCE_FILES})

ADD_LIBRARY(encode STATIC IMPORTED)
SET_TARGET_PROPERTIES(encode PROPERTIES
IMPORTED_LOCATION /ClionProjects/Coder/libencode_linux_x86_64.a)
TARGET_LINK_LIBRARIES(Coder encode)


And i had an error:
Error:Cannot specify link libraries for target "Code" which is not built by this project.


Can somebody help me to link my libencode_linux_x86_64.a file with CMake?

Answer
project(name)                       #Project name

cmake_minimum_required(             # Start
    VERSION 3.0.2                   # Cmake minimum version
)                                   # End

include_directories(                # Start
    "../../extern/mysql"            # Path to files to include
)                                   # End

link_directories(                   # Start
    "path/to/encode_linux_x86_64"   # Path where is lib.a located
)                                   # end

add_compile_options(                # Start
    -fstack-protector               # Compile flag 1
    -Wno-invalid-source-encoding    # Compile flag 2
)                                   # End

add_executable(                     # Start
    name_executable                 # Name of executable after compile
    main.cpp                        # file 1
    coder.cpp                       # file 2
)                                   # end

target_link_libraries(              # Start
game                                # Name of executable 
LINK_PUBLIC                         # Link Type
encode_linux_x86_64                 # Name of library without "lib" prefix
)                                   # End

Here you go, comment say all. EDITED