From 0f262056cdc114738a8da3947185a89d10ade581 Mon Sep 17 00:00:00 2001
From: veega2022 <zhuweijia@huawei.com>
Date: Tue, 12 Nov 2024 19:23:50 +0800
Subject: [PATCH 07/27] hikptool: Support static compilation for hikptool

Support static compilation by add the option ENABLE_STATIC,
Please refer to the following usage methods:

```
cmake ${src} -DENABLE_STATIC=1
```

Signed-off-by: Chengchang Tang <tangchengchang@huawei.com>
---
 CMakeLists.txt                       | 14 +++++++++++++-
 libhikptdev/src/rciep/CMakeLists.txt |  6 +++++-
 2 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index cbd063c..f2ffe6c 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -26,6 +26,8 @@ macro(get_header_dir_recurse HEADER_DIR_LIST)
     set(${HEADER_DIR_LIST} ${DIR_LIST})
 endmacro()
 
+option(ENABLE_STATIC "Make tool run as independently as possible" off)
+
 file(GLOB_RECURSE HIKPTOOL_SRC
 	${CMAKE_CURRENT_SOURCE_DIR}/cxl/*.c
 	${CMAKE_CURRENT_SOURCE_DIR}/net/*.c
@@ -38,13 +40,23 @@ file(GLOB_RECURSE HIKPTOOL_SRC
 	${CMAKE_CURRENT_SOURCE_DIR}/tool_lib/*.c
 	${CMAKE_CURRENT_SOURCE_DIR}/hikp_init_main.c
 	)
+
 add_subdirectory(libhikptdev)
 add_executable(hikptool ${HIKPTOOL_SRC})
 get_header_dir_recurse(HIKPTOOL_HEADER_DIR)
 target_include_directories(hikptool PRIVATE ${HIKPTOOL_HEADER_DIR})
 target_link_directories(hikptool PRIVATE ${CMAKE_INSTALL_PREFIX}/lib)
 target_link_libraries(hikptool PRIVATE KPTDEV_SO)
+if (ENABLE_STATIC)
+    # I don¡¯t know why, but once you add double quotes to these
+    # link parameters, an error will be reported.
+    set(EXT_LINK_FLAGS -static-libgcc -static-libstdc++ -static)
+    set_target_properties(hikptool PROPERTIES LINK_SEARCH_START_STATIC ON)
+    set_target_properties(hikptool PROPERTIES LINK_SEARCH_END_STATIC ON)
+else()
+    set(EXT_LINK_FLAGS "-fPIE")
+endif()
 target_link_options(hikptool PRIVATE
-	-Wl,-z,relro,-z,now -Wl,-z,noexecstack -fPIE -pie
+	-Wl,-z,relro,-z,now -Wl,-z,noexecstack -pie ${EXT_LINK_FLAGS}
 	-s -lpthread -ldl -lm -lrt -T ${CMAKE_CURRENT_SOURCE_DIR}/hikp_register.ld)
 install(TARGETS hikptool RUNTIME DESTINATION bin OPTIONAL)
diff --git a/libhikptdev/src/rciep/CMakeLists.txt b/libhikptdev/src/rciep/CMakeLists.txt
index 5017f5b..e3f96c0 100644
--- a/libhikptdev/src/rciep/CMakeLists.txt
+++ b/libhikptdev/src/rciep/CMakeLists.txt
@@ -13,7 +13,11 @@ cmake_minimum_required(VERSION 3.0.0)
 
 set(KPTDEV_SO_NAME hikptdev)
 
-add_library(KPTDEV_SO SHARED hikpt_rciep.c)
+if (ENABLE_STATIC)
+    add_library(KPTDEV_SO STATIC hikpt_rciep.c)
+else()
+    add_library(KPTDEV_SO SHARED hikpt_rciep.c)
+endif()
 
 target_include_directories(KPTDEV_SO PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../../include)
 
-- 
2.45.0.windows.1

