reworking examples and adding more modules to cmake/ folder

This commit is contained in:
brenozd
2024-10-24 20:14:44 -03:00
parent bc3f6a97a6
commit f240e70f03
37 changed files with 809 additions and 389 deletions

View File

@@ -1,7 +1,7 @@
---
Language: Cpp
# BasedOnStyle: Google
AccessModifierOffset: -1
# BasedOnStyle: LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
@@ -33,7 +33,7 @@ AlignConsecutiveShortCaseStatements:
AcrossEmptyLines: false
AcrossComments: false
AlignCaseColons: false
AlignEscapedNewlines: Left
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments:
Kind: Always
@@ -44,13 +44,13 @@ AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: MultiLine
AttributeMacros:
- __capability
BinPackArguments: true
@@ -92,7 +92,7 @@ CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
@@ -104,29 +104,25 @@ ForEachMacros:
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Regroup
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^<ext/.*\.h>'
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*\.h>'
Priority: 1
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '([-_](test|unittest))?$'
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: true
IndentCaseLabels: false
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
@@ -145,7 +141,7 @@ IntegerLiteralSeparator:
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
KeepEmptyLinesAtTheStartOfBlocks: true
KeepEmptyLinesAtEOF: false
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
@@ -153,14 +149,14 @@ MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PackConstructorInitializers: NextLine
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
@@ -168,40 +164,10 @@ PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
PPIndentWidth: -1
QualifierAlignment: Leave
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
- ParseTestProto
- ParsePartialTestProto
CanonicalDelimiter: pb
BasedOnStyle: google
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
@@ -238,7 +204,7 @@ SpaceBeforeParensOptions:
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpacesBeforeTrailingComments: 2
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
@@ -251,7 +217,7 @@ SpacesInParensOptions:
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Auto
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:

View File

@@ -50,7 +50,7 @@ format:
_help_max_subgroups_hwrap:
- If an argument group contains more than this many sub-groups
- (parg or kwarg groups) then force it to a vertical layout.
max_subgroups_hwrap: 2
max_subgroups_hwrap: 3
_help_max_pargs_hwrap:
- If a positional argument group contains more than this many
- arguments, then force it to a vertical layout.
@@ -91,7 +91,7 @@ format:
_help_max_lines_hwrap:
- If a candidate layout is wrapped horizontally but it exceeds
- this many lines, then reject the layout.
max_lines_hwrap: 2
max_lines_hwrap: 3
_help_line_ending:
- What style line endings to use in the output.
line_ending: unix
@@ -168,7 +168,7 @@ markup:
canonicalize_hashrulers: true
_help_enable_markup:
- enable comment markup parsing and reflow
enable_markup: true
enable_markup: false
_help_lint: Options affecting the linter
lint:
_help_disabled_codes:

View File

@@ -1,19 +1,42 @@
cmake_minimum_required(VERSION 3.13)
set(CMAKE_CXX_STANDARD 17)
cmake_minimum_required(VERSION 3.30 FATAL_ERROR)
cmake_policy(VERSION 3.30)
project(boilerplate LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 98)
set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_STANDARD_REQUIRED OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
option(BUILD_TESTS "Build tests" OFF)
option(BUILD_DOCS "Build documentation" OFF)
option(DISABLE_LOGGING "Disables all logging" OFF)
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
enable_testing()
include(CheckCompileOptions)
include(FetchPlog)
include(FetchArgparse)
include(FetchLibbacktrace)
execute_process(
COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/version.sh
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE EXAMPLE_PROJECT_VERSION)
if(BUILD_TESTS)
enable_testing()
include(FetchGoogleTest)
add_subdirectory(tests)
endif()
if(DISABLE_LOGGING)
message(STATUS "Disabling all logs")
add_compile_definitions("PLOG_DISABLE_LOGGING=1")
endif()
if(BUILD_DOCS)
message(STATUS "Building documentation")
add_subdirectory(docs)
endif()
project(
example_project
VERSION ${EXAMPLE_PROJECT_VERSION}
LANGUAGES CXX)
add_subdirectory(src)
add_subdirectory(tests)
if(CMAKE_BUILD_TYPE STREQUAL "Release" OR CMAKE_BUILD_TYPE STREQUAL "MinSizeRel")
include(StripAll)
endif()

View File

@@ -1,3 +1,2 @@
# mqttd
# C/C++ Boilerplate Code
A MQTT 5.0 Broker written in C++

View File

@@ -0,0 +1,140 @@
include(CheckCompilerFlag)
include(CheckLinkerFlag)
set(COMPILE_FLAGS "")
set(LINK_FLAGS "")
function(check_and_add_compiler_flags flags_list)
set(supported_flags)
foreach(flag ${flags_list})
string(REPLACE ";" "_" flag_var ${flag})
check_compiler_flag(C "${flag}" "HAVE_FLAG_${flag_var}")
if(HAVE_FLAG_${flag_var})
list(APPEND supported_flags ${flag})
endif()
endforeach()
set(COMPILE_FLAGS ${supported_flags} PARENT_SCOPE)
endfunction()
function(check_and_add_linker_flags flags_list)
set(supported_flags)
foreach(flag ${flags_list})
string(REPLACE ";" "_" flag_var ${flag})
check_linker_flag(C "${flag}" "HAVE_LINKER_FLAG_${flag_var}")
if(HAVE_LINKER_FLAG_${flag_var})
list(APPEND supported_flags ${flag})
endif()
endforeach()
set(LINK_FLAGS ${supported_flags} PARENT_SCOPE)
endfunction()
set(GENERAL_COMPILE_FLAGS
# Enable warnings for constructs often associated with defects
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#enable-additional-format-function-warnings
"-Wall"
"-Wextra"
# Enable additional format function warnings
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#enable-additional-format-function-warnings
"-Wformat=2"
"-Wformat-security"
# Enable implicit conversion warnings
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#enable-implicit-conversion-warnings
"-Wconversion"
"-Wsign-conversion"
# Enable warning about trampolines that require executable stacks
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#enable-warning-about-trampolines-that-require-executable-stacks
"-Wtrampolines"
# Warn about implicit fallthrough in switch statements
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#warn-about-implicit-fallthrough-in-switch-statements
"-Wimplicit-fallthrough"
# Treat obsolete C constructs as errors
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#-Werror=implicit
"-Werror=implicit"
"-Werror=incompatible-pointer-types"
"-Werror=int-conversion")
# Flags enabled only on Release Mode
set(RELEASE_COMPILE_FLAGS
# Keeps only relevant symbols available to the library users
"-fvisibility=hidden"
"-fvisibility-inlines-hidden"
"-ffunction-sections"
"-fdata-sections"
# Enable code instrumentation of control-flow transfers to increase program security by checking that target addresses of
# control-flow transfer instructions are valid
# https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html#index-fcf-protection
"-fcf-protection=full"
# Enable run-time checks for stack-based buffer overflows
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#enable-run-time-checks-for-stack-based-buffer-overflows
# "-fstack-protector-strong"
# Build as position-independent code
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#build-as-position-independent-code
"-pie"
"-fPIE"
# Enable run-time checks for variable-size stack allocation validity
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#enable-run-time-checks-for-variable-size-stack-allocation-validity
"-fstack-clash-protection"
# Enable strict flexible arrays
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#enable-strict-flexible-arrays
"-fstrict-flex-arrays=3"
# Precondition checks for C++ standard library calls
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#precondition-checks-for-c-standard-library-calls
"-D_GLIBCXX_ASSERTIONS"
# Do not delete null pointer checks
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#do-not-delete-null-pointer-checks
"-fno-delete-null-pointer-checks"
# Integer overflow may occur
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#integer-overflow-may-occur
"-fno-strict-overflow"
# Do not assume strict aliasing
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#do-not-assume-strict-aliasing
"-fno-strict-aliasing"
# Perform trivial auto variable initialization
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#perform-trivial-auto-variable-initialization
"-ftrivial-auto-var-init=zero"
# Enable exception propagation to harden multi-threaded C code
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#enable-exception-propagation-to-harden-multi-threaded-c-code
"-fexceptions"
# Fortify sources for unsafe libc usage and buffer overflows
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#fortify-sources-for-unsafe-libc-usage-and-buffer-overflows
"-U_FORTIFY_SOURCE"
"-D_FORTIFY_SOURCE=3")
set(RELEASE_LINKER_FLAGS
"-Wl,-z,relro,-z,now"
# Enable data execution prevention
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#enable-data-execution-prevention
"-Wl,-z,noexecstack"
# Restrict dlopen calls to shared objects
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#restrict-dlopen-calls-to-shared-objects
"-Wl,-z,nodlopen"
# Allow linker to omit libraries specified on the command line to link against if they are not used
# https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html#allow-linker-to-omit-libraries-specified-on-the-command-line-to-link-against-if-they-are-not-used
"-Wl,--as-needed"
"-Wl,--no-copy-dt-needed-entries"
"--strip-all")
# Flags enabled only on Debug Mode
set(DEBUG_COMPILE_FLAGS "-g3" "-Og" "-fno-omit-frame-pointer" "-fno-optimize-sibling-calls" "-fno-common")
set(DEBUG_LINKER_FLAGS "-rdynamic")
set(CONFIG_COMPILE_FLAGS ${GENERAL_COMPILE_FLAGS})
set(CONFIG_LINKER_FLAGS ${GENERAL_LINKER_FLAGS})
if(NOT CMAKE_BUILD_TYPE EQUAL "Debug")
list(APPEND CONFIG_COMPILE_FLAGS ${RELEASE_COMPILE_FLAGS})
list(APPEND CONFIG_LINKER_FLAGS ${RELEASE_LINKER_FLAGS})
elseif(CMAKE_BUILD_TYPE STREQUAL "Debug")
list(APPEND CONFIG_COMPILE_FLAGS ${DEBUG_COMPILE_FLAGS})
list(APPEND CONFIG_LINKER_FLAGS ${DEBUG_LINKER_FLAGS})
else()
message(WARNING "Unknown build type: ${CMAKE_BUILD_TYPE}. Using Debug flags by default.")
list(APPEND CONFIG_COMPILE_FLAGS ${DEBUG_COMPILE_FLAGS})
list(APPEND CONFIG_LINKER_FLAGS ${DEBUG_LINKER_FLAGS})
endif()
check_and_add_compiler_flags("${CONFIG_COMPILE_FLAGS}")
check_and_add_linker_flags("${CONFIG_LINKER_FLAGS}")
message(STATUS "Compile flags for ${CMAKE_BUILD_TYPE}: ${COMPILE_FLAGS}")
message(STATUS "Linker flags for ${CMAKE_BUILD_TYPE}: ${LINK_FLAGS}")

35
cmake/FetchArgparse.cmake Normal file
View File

@@ -0,0 +1,35 @@
include(FetchContent)
option(STATIC_ARGPARSE "Statically build and link argparse" ON)
if(NOT ARGPARSE_VERSION)
set(ARGPARSE_VERSION "682d4520b4bc2b646cdfcf078b2fed00b3d2da30")
endif()
message(STATUS "Fetching and configuring argparse version ${ARGPARSE_VERSION}")
set(FETCHCONTENT_QUIET TRUE)
if(STATIC_ARGPARSE)
set(ARGPARSE_STATIC ON CACHE STRING "" FORCE)
set(ARGPARSE_SHARED OFF CACHE STRING "" FORCE)
else()
set(ARGPARSE_STATIC OFF CACHE STRING "" FORCE)
set(ARGPARSE_SHARED ON CACHE STRING "" FORCE)
endif()
FetchContent_Declare(
argparse
GIT_REPOSITORY https://github.com/cofyc/argparse.git
GIT_TAG ${ARGPARSE_VERSION}
GIT_PROGRESS TRUE
OVERRIDE_FIND_PACKAGE)
FetchContent_MakeAvailable(argparse)
if(TARGET argparse_shared)
target_compile_options(argparse_shared PRIVATE ${COMPILE_FLAGS})
target_link_options(argparse_shared PRIVATE "${LINK_FLAGS}")
endif()
if(TARGET argparse_static)
target_compile_options(argparse_static PRIVATE ${COMPILE_FLAGS})
target_link_options(argparse_static PRIVATE "${LINK_FLAGS}")
endif()

View File

@@ -1,47 +1,32 @@
include(FetchContent)
if(NOT C_ARES_VERSION)
set(C_ARES_VERSION "cares-1_17_2")
if(NOT CARES_VERSION)
set(CARES_VERSION "v1.33")
endif()
message(STATUS "Fetching and configuring c-ares version ${C_ARES_VERSION}")
message(STATUS "Fetching and configuring c-ares version ${CARES_VERSION}")
set(FETCHCONTENT_QUIET TRUE)
set(CARES_BUILD_TESTS OFF CACHE STRING "" FORCE)
set(CARES_BUILD_CONTAINER_TESTS OFF CACHE STRING "" FORCE)
set(CARES_BUILD_TOOLS OFF CACHE STRING "" FORCE)
set(CARES_SYMBOL_HIDING ON CACHE STRING "" FORCE)
set(CARES_THREADS OFF CACHE STRING "" FORCE)
set(CARES_COVERAGE OFF CACHE STRING "" FORCE)
set(CARES_BUILD_TESTS OFF CACHE INTERNAL "")
set(CARES_BUILD_CONTAINER_TESTS OFF CACHE INTERNAL "")
set(CARES_BUILD_TOOLS OFF CACHE INTERNAL "")
set(CARES_STATIC OFF CACHE STRING "" FORCE)
set(CARES_STATIC_PIC OFF CACHE STRING "" FORCE)
set(CARES_SHARED ON CACHE STRING "" FORCE)
if(STATIC_CARES)
set(CARES_SHARED OFF CACHE INTERNAL "")
set(CARES_STATIC ON CACHE INTERNAL "")
set(CARES_STATIC_PIC ON CACHE INTERNAL "")
else()
set(CARES_SHARED ON CACHE INTERNAL "")
set(CARES_STATIC OFF CACHE INTERNAL "")
set(CARES_STATIC_PIC OFF CACHE INTERNAL "")
set(CARES_STATIC ON CACHE STRING "" FORCE)
set(CARES_STATIC_PIC ON CACHE STRING "" FORCE)
set(CARES_SHARED OFF CACHE STRING "" FORCE)
endif()
FetchContent_Declare(
c-ares GIT_REPOSITORY https://github.com/c-ares/c-ares.git GIT_TAG ${C_ARES_VERSION} GIT_PROGRESS TRUE OVERRIDE_FIND_PACKAGE
)
FetchContent_MakeAvailable(c-ares)
add_custom_target(
c-ares-symbolic-link
DEPENDS c-ares
COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_SOURCE_DIR}/src/c-ares-libs
# Note that ${CMAKE_SOURCE_DIR}/src/c-ares-libs/c-ares does not have a '/' at the end, this is intentional!
# If a '/' is placed at the end, the symlink will try create the link inside src/c-ares-libs/c-ares/ folder
# Without a '/', it will create a symlink called kperf inside ${CMAKE_SOURCE_DIR}/src/c-ares-libs/c-ares
COMMAND ${CMAKE_COMMAND} -E create_symlink ${c-ares_SOURCE_DIR} ${CMAKE_SOURCE_DIR}/src/c-ares-libs/c-ares
COMMENT "Creates a kperf symlink inside tangram source folder"
)
add_custom_target(
clean-c-ares
COMMAND ${CMAKE_COMMAND} -E remove_directory ${CMAKE_SOURCE_DIR}/src/c-ares-libs
COMMENT "Remove c-ares-libs folder"
)
set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${CMAKE_SOURCE_DIR}/src/c-ares-libs)
cares
GIT_REPOSITORY https://github.com/c-ares/c-ares.git
GIT_TAG ${CARES_VERSION}
GIT_PROGRESS TRUE
OVERRIDE_FIND_PACKAGE)
FetchContent_MakeAvailable(cares)

View File

@@ -1,9 +0,0 @@
include(FetchContent)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.5.2)
FetchContent_MakeAvailable(Catch2)
list(APPEND CMAKE_MODULE_PATH ${catch2_SOURCE_DIR}/extras)

View File

@@ -1,45 +1,42 @@
include(FetchContent)
if(NOT LIBCURL_VERSION)
set(LIBCURL_VERSION "curl-8_8_0")
set(FETCHCONTENT_QUIET TRUE)
set(BUILD_MISC_DOCS OFF CACHE STRING "" FORCE)
set(ENABLE_CURL_MANUAL OFF CACHE STRING "" FORCE)
set(BUILD_TESTING OFF CACHE STRING "" FORCE)
set(CURL_DISABLE_INSTALL ON CACHE STRING "" FORCE)
set(BUILD_LIBCURL_DOCS OFF CACHE STRING "" FORCE)
set(BUILD_SHARED_LIBS ON CACHE STRING "" FORCE)
set(BUILD_CURL_EXE OFF CACHE STRING "" FORCE)
set(BUILD_STATIC_CURL OFF CACHE STRING "" FORCE)
set(BUILD_STATIC_LIBS OFF CACHE STRING "" FORCE)
if(STATIC_CURL)
set(BUILD_SHARED_LIBS OFF CACHE STRING "" FORCE)
set(BUILD_STATIC_LIBS ON CACHE STRING "" FORCE)
endif()
find_package(CURL QUIET)
if(CURL_FOUND)
message(STATUS "cURL version ${CURL_VERSION_STRING} was found in your system.")
else()
message(STATUS "cURL was not found in your system. Fetching and configuring cURL version ${LIBCURL_VERSION}")
set(FETCHCONTENT_QUIET TRUE)
set(BUILD_MISC_DOCS OFF CACHE INTERNAL "")
set(ENABLE_CURL_MANUAL OFF CACHE INTERNAL "")
set(BUILD_TESTING OFF CACHE INTERNAL "")
set(CURL_DISABLE_INSTALL ON CACHE INTERNAL "")
set(BUILD_LIBCURL_DOCS OFF CACHE INTERNAL "")
set(BUILD_SHARED_LIBS ON CACHE INTERNAL "")
set(BUILD_CURL_EXE OFF CACHE INTERNAL "")
set(BUILD_STATIC_CURL OFF CACHE INTERNAL "")
set(BUILD_STATIC_LIBS OFF CACHE INTERNAL "")
if(BUILD_CURL_BIN)
if(STATIC_CURL)
set(BUILD_SHARED_LIBS OFF CACHE INTERNAL "")
set(BUILD_STATIC_LIBS ON CACHE INTERNAL "")
set(BUILD_STATIC_CURL ON CACHE STRING "" FORCE)
else()
set(BUILD_CURL_EXE ON CACHE STRING "" FORCE)
endif()
if(BUILD_CURL_BIN)
if(STATIC_CURL)
set(BUILD_STATIC_CURL ON CACHE INTERNAL "")
else()
set(BUILD_CURL_EXE ON CACHE INTERNAL "")
endif()
endif()
FetchContent_Declare(
CURL
GIT_REPOSITORY https://github.com/curl/curl.git
GIT_TAG ${LIBCURL_VERSION}
GIT_PROGRESS TRUE
OVERRIDE_FIND_PACKAGE)
FetchContent_MakeAvailable(CURL)
endif()
FetchContent_Declare(
curl
GIT_REPOSITORY https://github.com/curl/curl.git
GIT_TAG ${LIBCURL_VERSION}
GIT_PROGRESS TRUE
OVERRIDE_FIND_PACKAGE)
FetchContent_MakeAvailable(curl)
if(NOT TARGET CURL::libcurl_static AND TARGET CURL::curl)
add_library(CURL::libcurl_static ALIAS CURL::curl)
endif()
if(NOT TARGET CURL::libcurl_shared AND TARGET CURL::curl)
add_library(CURL::libcurl_shared ALIAS CURL::curl)
endif()

View File

@@ -0,0 +1,14 @@
include(FetchContent)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.8.x # 1.8.x works with pré C++11 compilers, which allows us to compile tests for toolchains
GIT_SHALLOW TRUE
OVERRIDE_FIND_PACKAGE)
FetchContent_MakeAvailable(googletest)
# Workaround for warning treated as error in gtest
# https://stackoverflow.com/a/75379860
target_compile_options(gtest PRIVATE "-w")

View File

@@ -1,36 +0,0 @@
include(FetchContent)
if(NOT JSONC_VERSION)
set(JSONC_VERSION "json-c-0.17-20230812")
endif()
find_package(json-c QUIET CONFIG)
if(json-c_FOUND)
message(STATUS "json-c version ${json-c_VERSION} was found in your system.")
else()
message(STATUS "json-c was not found in your system. Fetching and configuring json-c version ${JSONC_VERSION}")
set(FETCHCONTENT_QUIET TRUE)
if(STATIC_JSONC)
set(BUILD_SHARED_LIBS OFF CACHE INTERNAL "")
set(BUILD_STATIC_LIBS ON CACHE INTERNAL "")
else()
set(BUILD_SHARED_LIBS ON CACHE INTERNAL "")
set(BUILD_STATIC_LIBS OFF CACHE INTERNAL "")
endif()
# Hack to install JSON C headers where we want
set(CMAKE_INSTALL_PREFIX ${FETCHCONTENT_BASE_DIR}/json-c-install/ CACHE INTERNAL "" FORCE)
set(json-c_INSTALL_DIR ${CMAKE_INSTALL_PREFIX})
FetchContent_Declare(
json-c GIT_REPOSITORY https://github.com/json-c/json-c.git GIT_TAG ${JSONC_VERSION} GIT_PROGRESS TRUE OVERRIDE_FIND_PACKAGE
)
FetchContent_MakeAvailable(json-c)
add_custom_target(
json-c-install DEPENDS json-c COMMAND ${CMAKE_COMMAND} --install ${json-c_BINARY_DIR} --prefix=${json-c_INSTALL_DIR}
COMMENT "Installing json-c"
)
endif()

29
cmake/FetchJsonCpp.cmake Normal file
View File

@@ -0,0 +1,29 @@
include(FetchContent)
set(FETCHCONTENT_QUIET TRUE)
set(JSONCPP_WITH_TESTS OFF CACHE STRING "" FORCE)
set(JSONCPP_WITH_POST_BUILD_UNITTEST OFF CACHE STRING "" FORCE)
set(JSONCPP_WITH_WARNING_AS_ERROR OFF CACHE STRING "" FORCE)
set(JSONCPP_WITH_PKGCONFIG_SUPPORT OFF CACHE STRING "" FORCE)
set(JSONCPP_WITH_CMAKE_PACKAGE OFF CACHE STRING "" FORCE)
if(STATIC_JSON_CPP)
set(BUILD_SHARED_LIBS OFF CACHE STRING "" FORCE)
set(BUILD_STATIC_LIBS ON CACHE STRING "" FORCE)
else()
set(BUILD_SHARED_LIBS ON CACHE STRING "" FORCE)
set(BUILD_STATIC_LIBS OFF CACHE STRING "" FORCE)
endif()
FetchContent_Declare(
jsoncpp
GIT_REPOSITORY https://github.com/open-source-parsers/jsoncpp.git
GIT_TAG 0.y.z
GIT_SHALLOW TRUE
OVERRIDE_FIND_PACKAGE)
FetchContent_MakeAvailable(jsoncpp)
if(TARGET jsoncpp_lib_static)
target_compile_options(jsoncpp_lib_static PRIVATE ${COMPILE_FLAGS} -fPIC)
target_link_options(jsoncpp_lib_static PRIVATE ${LINK_FLAGS})
endif()

View File

@@ -0,0 +1,13 @@
include(FetchContent)
set(FETCHCONTENT_QUIET TRUE)
set(BUILD_SHARED OFF CACHE STRING "" FORCE)
FetchContent_Declare(
libbacktrace
GIT_REPOSITORY git@github.com:brenozd/libbacktrace.git
GIT_TAG master
GIT_SHALLOW TRUE
OVERRIDE_FIND_PACKAGE)
FetchContent_MakeAvailable(libbacktrace)

View File

@@ -10,8 +10,7 @@ if(eclipse-paho-mqtt-c_FOUND)
else()
message(
STATUS
"Paho MQTT C was not found in your system. Fetching and configuring eclipse-paho-mqtt-c version ${PAHO_MQTT_C_VERSION}"
)
"Paho MQTT C was not found in your system. Fetching and configuring eclipse-paho-mqtt-c version ${PAHO_MQTT_C_VERSION}")
set(FETCHCONTENT_QUIET TRUE)
set(PAHO_WITH_SSL TRUE CACHE INTERNAL "")
@@ -27,8 +26,10 @@ else()
endif()
FetchContent_Declare(
eclipse-paho-mqtt-c GIT_REPOSITORY https://github.com/eclipse/paho.mqtt.c.git GIT_TAG ${PAHO_MQTT_C_VERSION}
GIT_PROGRESS TRUE OVERRIDE_FIND_PACKAGE
)
eclipse-paho-mqtt-c
GIT_REPOSITORY https://github.com/eclipse/paho.mqtt.c.git
GIT_TAG ${PAHO_MQTT_C_VERSION}
GIT_PROGRESS TRUE
OVERRIDE_FIND_PACKAGE)
FetchContent_MakeAvailable(eclipse-paho-mqtt-c)
endif()

10
cmake/FetchPlog.cmake Normal file
View File

@@ -0,0 +1,10 @@
include(FetchContent)
FetchContent_Declare(
plog
GIT_REPOSITORY https://github.com/SergiusTheBest/plog.git
GIT_TAG 1.1.10
GIT_SHALLOW TRUE
OVERRIDE_FIND_PACKAGE)
FetchContent_MakeAvailable(plog)

View File

@@ -16,16 +16,10 @@ Result Variables
indicates Autotools and associated programs are detected
#]=======================================================================]
find_program(
AUTOCONF_EXECUTABLE
NAMES autoconf
DOC "Autoconf")
find_program(AUTOCONF_EXECUTABLE NAMES autoconf DOC "Autoconf")
if(AUTOCONF_EXECUTABLE)
execute_process(
COMMAND ${AUTOCONF_EXECUTABLE} --version
RESULT_VARIABLE ret
OUTPUT_VARIABLE out)
execute_process(COMMAND ${AUTOCONF_EXECUTABLE} --version RESULT_VARIABLE ret OUTPUT_VARIABLE out)
message(DEBUG "${out}")
if(ret EQUAL 0)
string(REGEX MATCH "autoconf .*([0-9]+\\.[0-9]+)" _m "${out}")
@@ -33,28 +27,14 @@ if(AUTOCONF_EXECUTABLE)
endif()
endif()
find_program(
AUTOMAKE_EXECUTABLE
NAMES automake
DOC "Automake")
find_program(AUTOMAKE_EXECUTABLE NAMES automake DOC "Automake")
find_program(
LIBTOOL_EXECUTABLE
NAMES glibtool libtool NAMES_PER_DIR
DOC "libtool")
find_program(LIBTOOL_EXECUTABLE NAMES glibtool libtool NAMES_PER_DIR DOC "libtool")
find_program(
M4_EXECUTABLE
NAMES gm4 m4 NAMES_PER_DIR
DOC "M4")
find_program(M4_EXECUTABLE NAMES gm4 m4 NAMES_PER_DIR DOC "M4")
find_program(
MAKE_EXECUTABLE
NAMES gmake make NAMES_PER_DIR
DOC "GNU Make")
find_program(MAKE_EXECUTABLE NAMES gmake make NAMES_PER_DIR DOC "GNU Make")
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
Autotools
VERSION_VAR AUTOCONF_VERSION
REQUIRED_VARS AUTOCONF_EXECUTABLE AUTOMAKE_EXECUTABLE MAKE_EXECUTABLE)
find_package_handle_standard_args(Autotools VERSION_VAR AUTOCONF_VERSION REQUIRED_VARS AUTOCONF_EXECUTABLE AUTOMAKE_EXECUTABLE
MAKE_EXECUTABLE)

View File

@@ -0,0 +1,127 @@
include(FetchContent)
# Verifica a instalação do OpenSSL no sistema
find_package(OpenSSL 1.0.2...1.1.1 QUIET)
if(OPENSSL_FOUND)
return()
endif()
# Diretórios para baixar e instalar o OpenSSL
set(OPENSSL_SOURCE_DIR ${FETCHCONTENT_BASE_DIR}/openssl-src)
if(CMAKE_CROSSCOMPILING)
set(OPENSSL_INSTALL_DIR ${CMAKE_SYSROOT})
set(SYSROOT_FLAG --sysroot=${CMAKE_SYSROOT})
else()
set(OPENSSL_INSTALL_DIR ${FETCHCONTENT_BASE_DIR}/openssl)
set(SYSROOT_FLAG "")
endif()
# Verifica se o OpenSSL já foi clonado e configura o repositório
if(EXISTS ${OPENSSL_SOURCE_DIR}/.git)
# Verifica a branch actual
execute_process(COMMAND git -C ${OPENSSL_SOURCE_DIR} rev-parse --abbrev-ref HEAD OUTPUT_VARIABLE CURRENT_BRANCH
OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_QUIET ERROR_QUIET)
# Define a branch desejada
set(DESIRED_BRANCH "OpenSSL_1_1_1w")
if(NOT "${CURRENT_BRANCH}" STREQUAL "${DESIRED_BRANCH}")
# Faz o checkout da branch desejada se necessário
execute_process(COMMAND git -C ${OPENSSL_SOURCE_DIR} checkout ${DESIRED_BRANCH} OUTPUT_QUIET
RESULT_VARIABLE CHECKOUT_STATUS)
if(NOT CHECKOUT_STATUS EQUAL 0)
message(FATAL_ERROR "Failed to checkout branch ${DESIRED_BRANCH} in OpenSSL")
endif()
# Atualiza o repositório para garantir que está na última versão
execute_process(COMMAND git -C ${OPENSSL_SOURCE_DIR} pull origin ${DESIRED_BRANCH} OUTPUT_QUIET RESULT_VARIABLE PULL_STATUS)
if(NOT PULL_STATUS EQUAL 0)
message(FATAL_ERROR "Failed to pull latest changes for branch ${DESIRED_BRANCH} in OpenSSL")
endif()
endif()
else()
# Clona o repositório do OpenSSL se ele não existir
execute_process(COMMAND git clone -b OpenSSL_1_1_1w --depth 1 https://github.com/openssl/openssl.git ${OPENSSL_SOURCE_DIR}
OUTPUT_QUIET RESULT_VARIABLE CLONE_STATUS)
if(NOT CLONE_STATUS EQUAL 0)
message(FATAL_ERROR "Failed to clone OpenSSL")
endif()
endif()
# Configura flags adicionais de compilação se necessário
if(NOT DEFINED OPENSSL_EXTRA_CONFIGURE_FLAGS)
set(OPENSSL_EXTRA_CONFIGURE_FLAGS "" CACHE STRING "" FORCE)
endif()
# Configura o target de acordo com o sistema (32-bit ou 64-bit)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
message(STATUS "Detected 64-bit target system based on toolchain.")
set(OPENSSL_TARGET_CONFIG "linux-generic64" CACHE STRING "" FORCE)
elseif(CMAKE_SIZEOF_VOID_P EQUAL 4)
message(STATUS "Detected 32-bit target system based on toolchain.")
set(OPENSSL_TARGET_CONFIG "linux-generic32" CACHE STRING "" FORCE)
else()
message(FATAL_ERROR "Unknown target architecture: pointer size is neither 4 nor 8.")
endif()
set(ENV{CC} "${CMAKE_C_COMPILER}")
set(ENV{CXX} "${CMAKE_CXX_COMPILER}")
set(ENV{LD} "${CMAKE_LINKER}")
# Executa o script de configuração do OpenSSL durante a fase de configuração do CMake
execute_process(
COMMAND ./Configure ${OPENSSL_TARGET_CONFIG} no-async no-dso no-hw no-engine no-unit-test ${OPENSSL_EXTRA_CONFIGURE_FLAGS}
${SYSROOT_FLAG} --prefix=${OPENSSL_INSTALL_DIR} --openssldir=${OPENSSL_SOURCE_DIR}
WORKING_DIRECTORY ${OPENSSL_SOURCE_DIR} RESULT_VARIABLE CONFIGURE_STATUS)
if(NOT CONFIGURE_STATUS EQUAL 0)
message(FATAL_ERROR "Failed to configure OpenSSL")
endif()
# Adiciona commandos personalizados de compilação para o OpenSSL
add_custom_command(
OUTPUT ${OPENSSL_INSTALL_DIR}/lib/libssl.a # Ou qualquer outro artefato importante (dinâmico ou estático)
COMMAND make clean depend
COMMAND make -j4 V=sc
COMMAND make install_sw
WORKING_DIRECTORY ${OPENSSL_SOURCE_DIR}
COMMENT "Building and installing OpenSSL")
# Define um alvo personalizado que depende da conclusão do build
add_custom_target(openssl ALL DEPENDS ${OPENSSL_INSTALL_DIR}/lib/libssl.a)
# Configura a vinculação de bibliotecas e a importação para OpenSSL (estático ou dinâmico)
if(OPENSSL_STATIC)
# Se for estático
add_library(OpenSSL::SSL STATIC IMPORTED)
set_target_properties(OpenSSL::SSL PROPERTIES IMPORTED_LOCATION ${OPENSSL_INSTALL_DIR}/lib/libssl.a
INTERFACE_INCLUDE_DIRECTORIES ${OPENSSL_INSTALL_DIR}/include)
add_library(OpenSSL::Crypto STATIC IMPORTED)
set_target_properties(OpenSSL::Crypto PROPERTIES IMPORTED_LOCATION ${OPENSSL_INSTALL_DIR}/lib/libcrypto.a
INTERFACE_INCLUDE_DIRECTORIES ${OPENSSL_INSTALL_DIR}/include)
set(OPENSSL_CRYPTO_LIBRARY ${OPENSSL_INSTALL_DIR}/lib/libcrypto.a)
set(OPENSSL_SSL_LIBRARY ${OPENSSL_INSTALL_DIR}/lib/libssl.a)
else()
# Se for dinâmico (compartilhado)
add_library(OpenSSL::SSL SHARED IMPORTED)
set_target_properties(OpenSSL::SSL PROPERTIES IMPORTED_LOCATION ${OPENSSL_INSTALL_DIR}/lib/libssl.so
INTERFACE_INCLUDE_DIRECTORIES ${OPENSSL_INSTALL_DIR}/include)
add_library(OpenSSL::Crypto SHARED IMPORTED)
set_target_properties(OpenSSL::Crypto PROPERTIES IMPORTED_LOCATION ${OPENSSL_INSTALL_DIR}/lib/libcrypto.so
INTERFACE_INCLUDE_DIRECTORIES ${OPENSSL_INSTALL_DIR}/include)
set(OPENSSL_CRYPTO_LIBRARY ${OPENSSL_INSTALL_DIR}/lib/libcrypto.so)
set(OPENSSL_SSL_LIBRARY ${OPENSSL_INSTALL_DIR}/lib/libssl.so)
endif()
# Adiciona dependências para garantir que as bibliotecas sejam compiladas antes do uso
add_dependencies(OpenSSL::SSL openssl)
add_dependencies(OpenSSL::Crypto openssl)
# Configura variáveis para que outros targets possam usar as bibliotecas do OpenSSL
set(OPENSSL_ROOT_DIR ${OPENSSL_INSTALL_DIR})
set(OPENSSL_INCLUDE_DIR ${OPENSSL_INSTALL_DIR}/include)
set(OPENSSL_LIBRARIES OpenSSL::SSL OpenSSL::Crypto)

View File

@@ -0,0 +1,16 @@
if(STATIC_CURL)
set(CURL_USE_STATIC_LIBS TRUE)
endif()
find_package(CURL QUIET)
if(CURL_FOUND)
message(STATUS "Found cURL: ${CURL_LIBRARIES} (found version \"${CURL_VERSION_STRING}\")")
return()
endif()
# If desired libcurl was not found, build from source
if(NOT LIBCURL_VERSION)
set(LIBCURL_VERSION "curl-8_8_0")
endif()
message(STATUS "Fetching and configuring cURL version ${LIBCURL_VERSION}")
include(FetchCurl)

View File

@@ -0,0 +1,14 @@
# Find libpcap
find_package(Pcap QUIET)
if(Pcap_FOUND)
message(STATUS "Found libpcap: ${Pcap_LIBRARIES} (found version \"${PCap_VERSION}\")")
return()
endif()
# If desired libpcap was not found, build from source
if(NOT LIBPCAP_VERSION)
set(LIBPCAP_VERSION "libpcap-1.10")
endif()
message(STATUS "Fetching and configuring libpcap version ${LIBPCAP_VERSION}")
include(FetchPcap)

29
cmake/StripAll.cmake Normal file
View File

@@ -0,0 +1,29 @@
# More at: https://www.technovelty.org/linux/stripping-shared-libraries.html
function(_get_all_cmake_targets out_var current_dir)
get_property(targets DIRECTORY ${current_dir} PROPERTY BUILDSYSTEM_TARGETS)
get_property(subdirs DIRECTORY ${current_dir} PROPERTY SUBDIRECTORIES)
foreach(subdir ${subdirs})
_get_all_cmake_targets(subdir_targets ${subdir})
list(APPEND targets ${subdir_targets})
endforeach()
set(${out_var} ${targets} PARENT_SCOPE)
endfunction()
_get_all_cmake_targets(all_targets ${PROJECT_SOURCE_DIR})
add_custom_target(strip_all ALL COMMENT "Stripping symbols from all executables and shared libraries")
foreach(target ${all_targets})
message(VERBOSE "[STRIP] Adding target: ${target}")
get_target_property(target_type ${target} TYPE)
if(target_type STREQUAL "EXECUTABLE" OR target_type STREQUAL "SHARED_LIBRARY" OR target_type STREQUAL "MODULE_LIBRARY")
add_custom_command(
TARGET strip_all
POST_BUILD
COMMAND ${CMAKE_STRIP} --strip-all $<TARGET_FILE:${target}>
COMMENT "Stripping symbols from ${target}")
endif()
endforeach()

44
docs/CMakeLists.txt Normal file
View File

@@ -0,0 +1,44 @@
if(NOT BUILD_DOCS)
return()
endif()
find_package(Doxygen REQUIRED doxygen OPTIONAL_COMPONENTS dot mscgen dia)
if(NOT DOXYGEN_FOUND)
message(ERROR "Doxygen is needed to build documentation, please install it")
endif()
set(DOXYGEN_ALPHABETICAL_INDEX NO)
set(DOXYGEN_BUILTIN_STL_SUPPORT YES)
set(DOXYGEN_CASE_SENSE_NAMES NO)
set(DOXYGEN_CLASS_DIAGRAMS YES)
set(DOXYGEN_DISTRIBUTE_GROUP_DOC YES)
set(DOXYGEN_EXCLUDE build)
set(DOXYGEN_EXTRACT_ALL YES)
set(DOXYGEN_EXTRACT_LOCAL_CLASSES NO)
set(DOXYGEN_FILE_PATTERNS *.hpp)
set(DOXYGEN_GENERATE_TREEVIEW YES)
set(DOXYGEN_HIDE_FRIEND_COMPOUNDS YES)
set(DOXYGEN_HIDE_IN_BODY_DOCS YES)
set(DOXYGEN_HIDE_UNDOC_CLASSES YES)
set(DOXYGEN_HIDE_UNDOC_MEMBERS YES)
set(DOXYGEN_JAVADOC_AUTOBRIEF YES)
set(DOXYGEN_QT_AUTOBRIEF YES)
set(DOXYGEN_QUIET YES)
set(DOXYGEN_RECURSIVE YES)
set(DOXYGEN_REFERENCED_BY_RELATION YES)
set(DOXYGEN_REFERENCES_RELATION YES)
set(DOXYGEN_SORT_BY_SCOPE_NAME YES)
set(DOXYGEN_SORT_MEMBER_DOCS NO)
set(DOXYGEN_SOURCE_BROWSER YES)
set(DOXYGEN_STRIP_CODE_COMMENTS NO)
set(DOXYGEN_USE_MDFILE_AS_MAINPAGE "${CMAKE_SOURCE_DIR}/README.md")
doxygen_add_docs(doc "${CMAKE_SOURCE_DIR}/README.md" "${CMAKE_SOURCE_DIR}/src/example_c" "${CMAKE_SOURCE_DIR}/src/example_cpp"
ALL COMMENT "Generate HTML documentation")
add_custom_target(
open-docs
COMMAND ${CMAKE_COMMAND} -E env xdg-open ${CMAKE_SOURCE_DIR}/build/docs/html/index.html
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/build/docs/html
COMMENT "Opening Doxygen documentation")

44
scripts/versioning.sh Executable file
View File

@@ -0,0 +1,44 @@
#!/bin/bash
set -e
# Script to Bump Version Numbers and Update File metadata
# This script updates the version numbers of a C/C++ project, specifically in `version.hpp` or `version.h`,
#and also updates information about compilation commits and build timestamps.
VERSION_FILE="$(find "$(pwd)" \( -iname "version.hpp" -o -iname "version.h" \))"
MAJOR=$(grep -oP '([a-zA-Z]*)_VERSION_MAJOR (\K[0-9]+)' "$VERSION_FILE")
MINOR=$(grep -oP '([a-zA-Z]*)_VERSION_MINOR (\K[0-9]+)' "$VERSION_FILE")
PATCH=$(grep -oP '([a-zA-Z]*)_VERSION_PATCH (\K[0-9]+)' "$VERSION_FILE")
_bump_version() {
case "$1" in
major)
MAJOR=$((MAJOR + 1))
;;
minor)
MINOR=$((MINOR + 1))
;;
patch)
PATCH=$((PATCH + 1))
;;
*)
echo "Unknown version semantic $1" >&2
exit 124
;;
esac
}
# Atualizar versões
[ "$#" -gt 0 ] && _bump_version "$1"
sed -i "s/\([a-zA-Z]\+\)_VERSION_MAJOR \([0-9]\+\)$/\1_VERSION_MAJOR $MAJOR/" "$VERSION_FILE"
sed -i "s/\([a-zA-Z]\+\)_VERSION_MINOR \([0-9]\+\)$/\1_VERSION_MINOR $MINOR/" "$VERSION_FILE"
sed -i "s/\([a-zA-Z]\+\)_VERSION_PATCH \([0-9]\+\)$/\1_VERSION_PATCH $PATCH/" "$VERSION_FILE"
# Atualizar informações de compilação
COMMIT_HASH=$(git rev-parse HEAD)
BUILD_TIMESTAMP=$(date +%s)
sed -i "s/\([a-zA-Z]\+\)_COMMIT_HASH \"[a-zA-Z0-9]\+\"/\1_COMMIT_HASH \"$COMMIT_HASH\"/" "$VERSION_FILE"
sed -i "s/\([a-zA-Z]\+\)_BUILD_TIMESTAMP [0-9]\+/\1_BUILD_TIMESTAMP $BUILD_TIMESTAMP/" "$VERSION_FILE"
# Exibir versão atualizada
printf "%d.%d.%d" "$MAJOR" "$MINOR" "$PATCH"

View File

@@ -1,4 +1,2 @@
add_subdirectory(example)
add_executable(example_project main.cpp)
target_link_libraries(example_project PRIVATE example_lib)
target_include_directories(example_project PUBLIC "${PROJECT_BINARY_DIR}")
add_subdirectory(example_c)
# add_subdirectory(example_cpp)

View File

@@ -1,5 +0,0 @@
FILE(GLOB CPP_FILES CONFIGURE_DEPENDS *.cpp)
FILE(GLOB HPP_FILES CONFIGURE_DEPENDS *.hpp)
add_library(example_lib ${CPP_FILES})
target_include_directories(example_lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

View File

@@ -1,29 +0,0 @@
#include "example.hpp"
int Calculator::add(int a, int b) {
return a + b;
}
int Calculator::sub(int a, int b) {
return a - b;
}
int Calculator::mul(int a, int b) {
return a * b;
}
int Calculator::div(int a, int b) {
if (b != 0) {
return a / b;
} else {
return 0;
}
}
int Calculator::mod(int a, int b) {
if (b != 0) {
return a % b;
} else {
return 0;
}
}

View File

@@ -1,13 +0,0 @@
#ifndef CALCULATOR_HPP
#define CALCULATOR_HPP
class Calculator {
public:
int add(int a, int b);
int sub(int a, int b);
int mul(int a, int b);
int div(int a, int b);
int mod(int a, int b);
};
#endif // CALCULATOR_HPP

View File

@@ -0,0 +1,23 @@
add_executable(example_c main.c)
execute_process(
COMMAND ${PROJECT_SOURCE_DIR}/scripts/versioning.sh
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE EXAMPLE_C_VERSION)
message(STATUS "Building [example_c] version ${EXAMPLE_C_VERSION}")
target_compile_options(example_c PRIVATE "${COMPILE_FLAGS}")
target_link_options(example_c PRIVATE "${LINK_FLAGS}")
file(GLOB C_FILES CONFIGURE_DEPENDS *.c)
file(GLOB H_FILES CONFIGURE_DEPENDS *.h)
target_sources(example_c PRIVATE ${C_FILES} PUBLIC ${H_FILES})
target_include_directories(example_c PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(example_c backtrace)
if(STATIC_ARGPARSE)
target_link_libraries(example_c argparse_static)
else()
target_link_libraries(example_c argparse_shared)
endif()

View File

@@ -0,0 +1,74 @@
#include "backtracer.h"
#include "backtrace.h"
#include "common.h"
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void *__backtrace_state = NULL;
void init_backtracer() {
__backtrace_state = backtrace_create_state(NULL, 0, _backtrace_error_callback_create, NULL);
if (!__backtrace_state) {
fprintf(stderr, "Failed to initialize backtrace engine\n");
abort();
}
}
int _backtrace_callback(void *UNUSED(data), uintptr_t pc, const char *filename, int lineno, const char *function) {
if (!function || !filename)
return 0;
printf("#%p - %s() at %s (line %d)\n", (void *)pc, function, filename, lineno);
return 0;
}
void _backtrace_error_callback(void *UNUSED(data), const char *msg, int errnum) {
printf("Error %d occurred when getting the stacktrace: %s", errnum, msg);
}
void _backtrace_error_callback_create(void *UNUSED(data), const char *msg, int errnum) {
printf("Error %d occurred when initializing the stacktrace: %s", errnum, msg);
}
void _print_backtrace() {
if (!__backtrace_state) {
printf("Make sure init_backtracer() is called before calling print_stack_trace()\n");
abort();
}
backtrace_full((struct backtrace_state *)__backtrace_state, 0, _backtrace_callback, _backtrace_error_callback, NULL);
}
#define N_SIGNALS 7
static void signal_handler_callback(int signum) {
printf("Error signal %s caught!\n", strsignal(signum));
_print_backtrace();
_exit(signum);
}
void register_signal_handlers() {
// Program Error Signals
// https://www.gnu.org/software/libc/manual/html_node/Program-Error-Signals.html
int signals_to_backtrace[N_SIGNALS] = {SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGABRT, SIGTRAP, SIGSYS};
// Blocking signals with set
sigset_t block_mask;
sigemptyset(&block_mask);
sigprocmask(SIG_BLOCK, &block_mask, NULL);
for (size_t i = 0; i < N_SIGNALS; i++) {
sigaddset(&block_mask, signals_to_backtrace[i]);
}
struct sigaction sigHandler;
memset(&sigHandler, 0, sizeof(sigHandler));
sigHandler.sa_handler = signal_handler_callback;
sigHandler.sa_mask = block_mask;
sigHandler.sa_flags = 0;
for (size_t i = 0; i < N_SIGNALS; i++) {
sigaction(signals_to_backtrace[i], &sigHandler, NULL);
}
}

View File

@@ -0,0 +1,13 @@
#ifndef INCLUDE_SRC_BACKTRACE_H_
#define INCLUDE_SRC_BACKTRACE_H_
#include "common.h"
#include <stdint.h>
void init_backtracer();
int _backtrace_callback(void *UNUSED(data), uintptr_t pc, const char *filename, int lineno, const char *function);
void _backtrace_error_callback(void *, const char *msg, int errnum);
void _backtrace_error_callback_create(void *, const char *msg, int errnum);
void _print_backtrace();
void register_signal_handlers();
#endif // INCLUDE_SRC_BACKTRACE_H_

16
src/example_c/common.h Normal file
View File

@@ -0,0 +1,16 @@
#ifndef INCLUDE_SRC_COMMON_H_
#define INCLUDE_SRC_COMMON_H_
#ifdef __GNUC__
#define UNUSED(x) UNUSED_##x __attribute__((__unused__))
#else
#define UNUSED(x) UNUSED_##x
#endif
#ifdef __GNUC__
#define UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_##x
#else
#define UNUSED_FUNCTION(x) UNUSED_##x
#endif
#endif // INCLUDE_SRC_COMMON_H_

17
src/example_c/main.c Normal file
View File

@@ -0,0 +1,17 @@
#include "backtracer.h"
#include <stdio.h>
#include <stdlib.h>
#include "version.h"
#include "common.h"
void f3() { abort(); }
void f2() { f3(); }
void f1() { f2(); }
int main(int UNUSED(argc), char *UNUSED(argv[])) {
register_signal_handlers();
init_backtracer();
printf("Example C Version %s\n", VERSION);
f1();
}

15
src/example_c/version.h Normal file
View File

@@ -0,0 +1,15 @@
#ifndef INCLUDE_EXAMPLE_C_VERSION_H_
#define INCLUDE_EXAMPLE_C_VERSION_H_
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define VERSION TOSTRING(EXAMPLE_C_VERSION_MAJOR) "." TOSTRING(EXAMPLE_C_VERSION_MINOR) "." TOSTRING(EXAMPLE_C_VERSION_PATCH)
#define EXAMPLE_C_VERSION_MAJOR 1
#define EXAMPLE_C_VERSION_MINOR 2
#define EXAMPLE_C_VERSION_PATCH 3
#define EXAMPLE_C_COMMIT_HASH cd01d7d8d36862bc00ae88f7cd185c352a7b7eda
#define EXAMPLE_C_BUILD_TIMESTAMP 1729811627
#endif // INCLUDE_EXAMPLE_C_VERSION_H_

View File

@@ -1,19 +0,0 @@
#include "version.hpp"
#include "example.hpp"
#include <iostream>
int main(int argc, char *argv[]) {
std::cout << "Example Version " << MQTTD_VERSION_MAJOR << "."
<< MQTTD_VERSION_MINOR << "."
<< MQTTD_VERSION_PATCH << std::endl;
Calculator calc;
std::cout << "add(10,4): " << calc.add(10,4) << std::endl;
std::cout << "sub(10,4): " << calc.sub(10,4) << std::endl;
std::cout << "mul(10,4): " << calc.mul(10,4) << std::endl;
std::cout << "div(10,4): " << calc.div(10,4) << std::endl;
std::cout << "mod(10,4): " << calc.mod(10,4) << std::endl;
return 0;
return 1;
}

View File

@@ -1,5 +0,0 @@
#define MQTTD_VERSION_MAJOR 0
#define MQTTD_VERSION_MINOR 0
#define MQTTD_VERSION_PATCH 0
#define MQTTD_COMMIT_HASH cd01d7d8d36862bc00ae88f7cd185c352a7b7eda
#define MQTTD_BUILD_TIMESTAMP 1705932908

View File

@@ -1,10 +0,0 @@
include(GetCatch2)
FILE(GLOB_RECURSE CPP_FILES CONFIGURE_DEPENDS *.cpp)
add_executable(tests ${CPP_FILES})
target_link_libraries(tests PRIVATE example_lib Catch2::Catch2WithMain)
include(CTest)
include(Catch)
catch_discover_tests(tests)

View File

@@ -1,35 +0,0 @@
#include <catch2/catch_test_macros.hpp>
#include "example.hpp"
TEST_CASE("CalculatorTest - Add", "[Calculator]") {
Calculator calc;
REQUIRE(calc.add(2, 3) == 5);
REQUIRE(calc.add(-2, 3) == 1);
REQUIRE(calc.add(0, 0) == 0);
}
TEST_CASE("CalculatorTest - Sub", "[Calculator]") {
Calculator calc;
REQUIRE(calc.sub(5, 3) == 2);
REQUIRE(calc.sub(3, 5) == -2);
REQUIRE(calc.sub(0, 0) == 0);
}
TEST_CASE("CalculatorTest - Mul", "[Calculator]") {
Calculator calc;
REQUIRE(calc.mul(2, 3) == 6);
REQUIRE(calc.mul(-2, 3) == -6);
REQUIRE(calc.mul(0, 5) == 0);
}
TEST_CASE("CalculatorTest - Div", "[Calculator]") {
Calculator calc;
REQUIRE(calc.div(6, 3) == 2);
REQUIRE(calc.div(5, 2) == 2);
}
TEST_CASE("CalculatorTest - Mod", "[Calculator]") {
Calculator calc;
REQUIRE(calc.mod(6, 4) == 2);
REQUIRE(calc.mod(5, 2) == 1);
}

View File

@@ -1,41 +0,0 @@
#!/bin/bash
set -e
VERSION_FILE="$(pwd)/src/version.hpp"
MAJOR=$(grep -oP 'MQTTD_VERSION_MAJOR \K[0-9]+' "$VERSION_FILE")
MINOR=$(grep -oP 'MQTTD_VERSION_MINOR \K[0-9]+' "$VERSION_FILE")
PATCH=$(grep -oP 'MQTTD_VERSION_PATCH \K[0-9]+' "$VERSION_FILE")
_bump_version() {
case "$1" in
major)
MAJOR=$((MAJOR + 1))
;;
minor)
MINOR=$((MINOR + 1))
;;
patch)
PATCH=$((PATCH + 1))
;;
*)
echo "Unknown version semantic $1" >&2
exit 124
;;
esac
}
# Atualizar versões
[ "$#" -gt 0 ] && _bump_version "$1"
sed -i "s/MQTTD_VERSION_MAJOR [0-9]\+/MQTTD_VERSION_MAJOR $MAJOR/" "$VERSION_FILE"
sed -i "s/MQTTD_VERSION_MINOR [0-9]\+/MQTTD_VERSION_MINOR $MINOR/" "$VERSION_FILE"
sed -i "s/MQTTD_VERSION_PATCH [0-9]\+/MQTTD_VERSION_PATCH $PATCH/" "$VERSION_FILE"
# Atualizar informações de compilação
COMMIT_HASH=$(git rev-parse HEAD)
BUILD_TIMESTAMP=$(date +%s)
sed -i "s/MQTTD_COMMIT_HASH [a-zA-Z0-9]\+/MQTTD_COMMIT_HASH $COMMIT_HASH/" "$VERSION_FILE"
sed -i "s/MQTTD_BUILD_TIMESTAMP [0-9]\+/MQTTD_BUILD_TIMESTAMP $BUILD_TIMESTAMP/" "$VERSION_FILE"
# Exibir versão atualizada
printf "%d.%d.%d" "$MAJOR" "$MINOR" "$PATCH"