如何访问其他 .cc 文件中命名空间中定义的函数
How to access function defined in namespace in other .cc file
我有一个名为test.cc
的文件
#include <stdio.h>
int doit(){
return 4;
}
namespace abc {
int returnIt(int a){
return a;
}
}
我可以使用doit((,但是如何在不使用.h文件的情况下在main.cc
命名空间中使用此函数:
using namespace abc;
int doit();
int main(int argc, const char * argv[]) {
cout<<returnIt(3)<<endl; // print 3
cout<<doit(); // print 4
return 0;
}
可以通过首先声明函数来调用函数。例:
namespace abc {
int returnIt(int a); // function declaration
}
int main() {
abc::returnIt(3); // the declared function can now be called
请注意,声明必须与程序中其他地方使用的声明完全相同。为了跨翻译单元实现相同的声明,通常将声明放入单独的文件(称为标头(中,并在需要声明时使用预处理器包含该文件。
您所需要的只是简单地在主函数之前编写函数。这样,编译器在 main 中遇到函数原型时已经处理了它们,并且可以验证函数调用。
int doit()
{
return 4;
}
int returnIt(int a)
{
return a;
}
int main(int argc, const char * argv[])
{
cout<<returnIt(3)<<endl; // print 3
cout<<doit(); // print 4
return 0;
}
一般来说,避免using namespace;
.它使代码可能由于不正确的变量/函数用法而被破坏或变得可读性降低。这是因为太多的符号可以占据相同的(全局(范围。
如果需要使用另一个库,正如user4581301所指出的那样,那么使用eerorika答案/方法可能更简单。
相关文章:
- 命名空间中具有.h和.cpp文件的类
- 使用 Clang++ 有没有办法将文件作为命名空间等包含?
- Qt C++:不同文件中同一命名空间的多个Q_NAMESPACE
- 不同C++文件中未命名命名空间中的名称可以引用同一个命名事物吗?
- 使用命名空间在另一个".cpp"文件中定义
- 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见
- 是否将命名空间范围文件本地 (.cpp) 常量放在匿名命名空间中
- 模板实现文件中的匿名命名空间
- C++-使用来自不同头文件、相同命名空间的枚举
- C++ 如何在 def 文件中指定命名空间
- 在实现文件中,我们应该更喜欢"using namespace"指令还是将实现包装在命名空间 { } 中?
- 在头文件中添加命名空间函数
- 在多个 cpp 文件中重用未命名的命名空间函数
- 使用匿名命名空间中的函数或另一个文件中的静态函数不应该出错吗?
- 跨命名空间的友元类和不同的.H 文件
- 我可以在应用程序之间更改 .proto 文件的命名空间吗?
- 试图将两个类放在同一命名空间中的单独文件中,但只有#1个#Class类作品
- C++中的头文件和命名空间
- 为什么主可执行文件和 dlopen 加载的共享库共享命名空间静态变量的一个副本?
- 包含所有命名空间 std 的文件