我正在尝试从另一个文件访问函数以在类定义中使用:
// math.cpp
int Sum(int a, int b){
return (a + b);
}
// my_class.cpp
#include <math.cpp>
#include <my_class.h>
int ComputeSomething() {
...
return ::Sum(num1, num2);
}
尽管我尽了最大的努力,但我无法让编译器吐出
::Sum has not been declared
或Sum was not declared in this scope.
之类的东西我正在尝试把头放在C++中的代码组织上,不胜感激。
可能值得注意的是,我正在为Arduino编程。
最佳答案
为了能够从用户定义的库访问函数,最好将该库分为.h(或.hpp)和.cpp文件。我了解您实际上已经做到了,但是为了找到解决方案,尝试了各种选择-其中包括.cpp文件。
不过,为了确保一切正常,函数和类的声明应放入.h文件中,最好由以下内容保护
#ifndef MY_H_FILE
#define MY_H_FILE
/* ..Declarations.. */
#endif
然后包含.h文件(我假设它名为my.h),可以使用
#include "my.h" // path relative to build directory
要么
#include <my.h> // path relative to any of the include paths
后者仅在编译器先前已知的包含路径上找到my.h时才有效(例如,在GCC中使用
-I
命令行选项指定的路径)。如果给定的.h文件的路径相对于您从其构建的目录的路径为,则前者可以工作。最后,请勿使用可能与系统库混淆的文件名(例如“math.h”),尤其是在使用
<...>
语法的情况下,因为include路径肯定会包含系统库头文件。关于c++ - 从类定义中的外部文件访问函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12256004/