首页 > 解决方案 > 如何访问其他 .cc 文件中命名空间中定义的函数

问题描述

我有一个文件名为test.cc

#include <stdio.h>

int doit(){
    return 4;
}

namespace abc {
    int returnIt(int a){
        return a;
    }
}

main.cc我可以使用 doit(),但是如何在不使用 .h 文件的情况下在我的命名空间中使用此函数:

using namespace abc;
int doit();
int main(int argc, const char * argv[]) {
    cout<<returnIt(3)<<endl; // print 3
    cout<<doit();            // print 4
    return 0;
}

标签: c++

解决方案


You can call functions by first declaring them. Example:

namespace abc {
    int returnIt(int a); // function declaration
}

int main() {
     abc::returnIt(3);     // the declared function can now be called

Note that the declaration must be exactly the same as used elsewhere in the program. To achieve identical declarations across translation units, it is conventional to put the declaration into a separate file (called a header) and include that file using the pre-processor whenever the declaration is needed.


推荐阅读