如何访问其他 .cc 文件中命名空间中定义的函数

How to access function defined in namespace in other .cc file

本文关键字:文件 命名空间 定义 函数 cc 其他 何访问 访问      更新时间:2023-10-16

我有一个名为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答案/方法可能更简单。