2017-06-12 76 views
-5

在我的代码中,我有一个std ::函数,它将在运行时根据用户输入定义,其他文件稍后将调用此函数。一个最小的(不)工作的代码的例子如下:包含在多个文件中时std :: function对象有多个定义错误?

在my_func.h文件,我有:

#pragma once 
#include <iostream> 
#include <functional> 

std::function<int(int)> inc_step; 

void SetIncFunc(); 

在my_func.cpp:

#include "my_func.h" 
void SetIncFunc() { 
    std::cout << "Input a number!" << std::endl; 
    int input; 
    std::cin >> input; 
    inc_step = [input](int x) {return x + input; }; 
} 

最后,在main.cpp中:

#include "my_func.h" 
int main() { 
    SetIncFunc(); 
    int x = 0; 
    std::cout << "before incrementing: " << x << std::endl; 
    x = inc_step(x); 
    std::cout << "after incrementing: " << x << std::endl; 
    return 0; 
} 

g ++连接器会给出如下错误:“inc_step'的多重定义”。 (也尝试在Visual Studio中,类似的错误)但是,如果我将所有代码移动到main.cpp文件中,那么它将编译并正确运行。

我很困惑,因为的#pragma一次应该阻止多个包裹,我只定义在SetIncFunc()函数...所以是有一个特殊的规则,包括的std ::函数对象?

在此先感谢!

+0

'#一次只编译一次'#include'sa头文件,每次编译。这与重复的头文件包含无关。 –

+0

你尝试过'extern'吗? –

+1

与'std :: function'无关。 – juanchopanza

回答

1

这是一个ODR违反定义头像这样的变量。在C++ 17可以将其标记inline解决这一问题,但在旧版本,你需要有头包含:

extern std::function<int(int)> inc_step; 

而源文件只有一个包含:

std::function<int(int)> inc_step; 
相关问题