【发布时间】:2018-07-24 14:47:11
【问题描述】:
我正在学习 C++,但我对内联行为感到困惑。在cppreference 上,我发现“包含在多个源文件中的函数必须是内联的”。他们的例子如下:
// header file
#ifndef EXAMPLE_H
#define EXAMPLE_H
// function included in multiple source files must be inline
inline int sum(int a, int b)
{
return a + b;
}
#endif
// source file #2
#include "example.h"
int a()
{
return sum(1, 2);
}
// source file #1
#include "example.h"
int b()
{
return sum(3, 4);
}
这让我有点困惑——我认为 ifndef 守卫正是在做这项工作,即防止多次包含同一个文件时出现问题。无论如何,我想测试一下,所以我准备了以下内容:
// Sum.h
#ifndef SUM_H
#define SUM_H
int sum(int a, int b);
#endif
// Sum.cpp
int sum(int a, int b){
return a + b;
}
// a.h
#ifndef A_H
#define A_H
int af();
#endif
// a.cpp
#include "sum.h"
int af(){
return sum(3, 4);
}
// b.h
#ifndef B_H
#define B_H
int bf();
#endif
// b.cpp
#include "sum.h"
int bf(){
return sum(1, 2);
}
// main.cpp
#include "sum.h"
#include "a.h"
#include "b.h"
#include <iostream>
int main() {
std::cout << af() + bf();
}
这可以正常工作。然后我在sum.cpp和sum.h中使用define sum函数内联,编译失败:
"sum(int, int)", referenced from:
bf() in b.cpp.o
af() in a.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
有人可以帮我澄清一下吗?
【问题讨论】:
-
包含保护防止在一个源文件中多次包含相同的标头。它们不会以任何方式影响包含在多个单独源文件中的标头的行为。
-
您的示例未在标头中定义函数。如果您需要有关错误的帮助,请显示失败的代码,而不是正常工作的代码。
标签: c++