我的C ++项目huzzah
有一个顶级标题include/huzzah.h
,用于定义两个函数
do_this
和do_that
。我在src/thing1.cpp
和src/thing2.cpp
中有多个这些函数的实现。鉴于以下单元测试,如何指定使用do_this或函数的do_that实现?也许在huzzah/CMakeLists.txt
,或通过main
args?
#include "huzzah.h"
int main(int argc, char **argv) {
auto a = do_this;
auto b = do_that;
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
}
(我不想把它们变成Thing1和Thing2类。)
答案 0 :(得分:0)
您可以为每个cpp文件创建2个共享库(在cmake中):
add_library(thing1 SHARED src/thing1.cpp)
add_library(thing2 SHARED src/thing2.cpp)
然后使用dlopen / dlsym动态加载它们(不要将你的应用程序与这些库链接):
using do_this_f = decltype(&do_this);
auto handle = dlopen( "libthing1.so", RTLD_LAZY );
auto do_this_1 = reinterpret_cast<do_this_f>( dlsym( handle, "do_this" ) );
do_this_1(); // calling do_this from libthing1.so
当然你需要添加错误处理,lib的正确路径等等
答案 1 :(得分:0)
比看起来容易:
#include "huzzah.h"
int main(int argc, char **argv) {
auto a = do_this();
auto b = do_that();
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
}
g++ -o test1 testmain.cpp src/thing1.cpp
g++ -o test2 testmain.cpp src/thing2.cpp