【问题标题】:How to include headefile and functions at runtime C++?如何在运行时 C++ 中包含头文件和函数?
【发布时间】:2013-10-11 09:11:40
【问题描述】:

我有两个基础项目。 Proj1.libProj2.exe。现在Proj2.exe 是启动项目,它将调用Proj1.lib。现在,当我将另一个Test.lib 添加到我的主项目时,其中包含Gtest。现在,要让Gtest 将所有测试用例累积到GTest 中,我们需要从Test.lib 中调用一个函数,并且该函数名称和头文件需要包含在Proj2.exe 中。然后Proj.exe 将被编译,然后它将编译Test.lib,然后它将执行测试用例。但现在我的要求是不要打扰Proj2.exe。当我想要时,我会附加/deachTest.libTest2.lib ... 等等。

下面将展示我们目前的做法。

Proj1.lib

x.c file
y.c file {/*App_Main_function()*/}

Proj2.exe

A.cpp
B.cpp file {/*Call App_Main_function();*/}
AttachTest.cpp {Test_Main();}

Test.lib

Test.cpp
{
    TestMain()
    {/*Body*/
        InitilizeGoogleTest();
        TEST_F(abc, ab)
        {}
    }
}

如果明天会有更多或新的测试库,那么我必须从Proj.exe 打开AttachTest.cpp 文件并添加函数名和头文件名。然后 Proj2.exe 将再次编译。

但我现在想保留Proj1.libProj2.exe 修复它们除了新的Test.lib 之外无法编译 如何做到这一点,

我已经想到了一种方法,我将拥有.xml 文件,该文件将具有函数名称。在Proj2.exe 中,我将拥有函数指针,它将在运行时调用它们。但是如何包含头文件呢??

请帮帮我。

【问题讨论】:

  • 您需要使用 DLL。

标签: c++ visual-studio-2010 linker static-libraries googletest


【解决方案1】:

您需要构建动态链接库 (DLL) 来做您想做的事。 .lib 库无法动态加载。

下面是一些如何使用这些库的示例代码,来自Wikipedia

#include <windows.h>
#include <stdio.h>

// DLL function signature
typedef double (*importFunction)(double, double);

int main(int argc, char **argv)
{
        importFunction addNumbers;
        double result;
        HINSTANCE hinstLib;

        // Load DLL file
        hinstLib = LoadLibrary(TEXT("Example.dll"));
        if (hinstLib == NULL) {
                printf("ERROR: unable to load DLL\n");
                return 1;
        }

        // Get function pointer
        addNumbers = GetProcAddress(hinstLib, "AddNumbers");
        if (addNumbers == NULL) {
                printf("ERROR: unable to find DLL function\n");
                FreeLibrary(hinstLib);
                return 1;
        }

        // Call function.
        result = addNumbers(1, 2);

        // Unload DLL file
        FreeLibrary(hinstLib);

        // Display result
        printf("The result was: %f\n", result);

        return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    相关资源
    最近更新 更多