选择同名的C ++顶级函数

时间:2018-05-01 18:40:41

标签: c++

我的C ++项目huzzah有一个顶级标题include/huzzah.h,用于定义两个函数 do_thisdo_that。我在src/thing1.cppsrc/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类。)

2 个答案:

答案 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