Singleton初始化问题:静态库编译后出现segfault排查
静态库链接后出现Segfault的排查问题
我正在开发一款用于简单任务的小型测试库,采用自注册方式定义测试用例。手动编译所有代码时运行正常,但生成静态库并单独编译示例代码后,出现了原因不明的segfault。
项目结构
Lib | |__include | |__lib.hpp |__src | |__lib.cpp |__examples | |__example.cpp |__Makefile
头文件内容
注:请忽略public的map,我清楚最终版本不应将其设为public
#include <string> #include <map> #include <functional> #define TEST(name, result_var_name, short_result_var_name, explanation_var) \ bool test_##name(std::string result_var_name); \ static bool test_##name##_registered = TestFactory::getInstance()->Register(#name, &test_##name, #result_var_name, #short_result_var_name); \ static bool test_##name##_description = TestFactory::getInstance()->RegisterExplanation(#result_var_name, explanation_var); \ bool test_##name(std::string result_var_name) #define RESULT_LONG(result_var_name, result) \ TestFactory::getInstance()->RegisterResult(result_var_name, result); #define RESULT_SHORT(result_var_name, result) \ TestFactory::getInstance()->RegisterResult(TestFactory::getInstance()->short_to_long_param[result_var_name], result); class TestFactory { private: TestFactory(); public: std::map<std::string, std::function<bool(std::string)>> Tests; std::map<std::string, std::string> short_to_long_param; std::map<std::string, std::string> param_to_testName; std::map<std::string, std::string> testName_to_result; std::map<std::string, std::string> param_to_explanation; static TestFactory* getInstance(); bool Register(std::string name, std::function<bool(std::string)> func, std::string long_param, std::string short_param); bool RegisterResult(std::string result_var_name, std::string result); bool RegisterExplanation(std::string result_var_name, std::string explanation); };
示例文件内容
#include "lib.hpp" #include <iostream> TEST(testing_test, foo, f, "This is a description of foo"){ try { return foo == "example"; } catch(const std::exception& e) { std::cerr << "Exception thrown in testing_test: " << e.what() << '\n'; return false; } };
Makefile内容
注:我不太擅长编写Makefile,敬请谅解
LIBNAME := libtest.a CXX := g++ BIN := bin SRC := src INCLUDE := include LIB := lib LIBRARIES := -ltest EXECUTABLE := example LIBRARY_SOURCES := $(SRC)/lib.o EXECUTABLE_SOURCES := examples/example.o CXXFLAGS := -Wall -Wextra -std=c++17 -ggdb -I$(INCLUDE) all: $(BIN)/$(EXECUTABLE) run: clean all clear ./$(BIN)/$(EXECUTABLE) $(LIB)/$(LIBNAME): $(LIBRARY_SOURCES) ar rcs $@ $^ $(BIN)/$(EXECUTABLE): $(LIB)/$(LIBNAME) $(CXX) $(CXXFLAGS) -I$(INCLUDE) -L$(LIB) $(EXECUTABLE_SOURCES) -o $@ $(LIBRARIES) clean: -rm -rf $(BIN)/* -rm -rf $(LIB)/*
核心问题
最初我使用全静态方法和变量,为避免初始化及内存问题改为Singleton模式,但在Register方法尝试访问Test map时仍出现segfault,请问可能的原因是什么?
编辑补充
手动执行以下编译步骤:
g++ -Iinclude -std=c++17 -c src/mxIntegration.cpp -o lib/manual_object_file.o ar rvs lib/manual_library.a lib/manual_object_file.o g++ -Iinclude examples/main.cpp lib/manual_object_file.o -o bin/manual_test_linking
生成的可执行文件可正常运行,我正在排查编译流程中的差异。
内容的提问来源于stack exchange,提问作者Marcos Alvarez
相关产品推荐
相关产品推荐

