简体   繁体   中英

namespace in C++ how to link?

My code has structure like this:

file1.cpp

namespace file1
{
  ...
  ...
}
int main()
{
  file2::func();
}

file2.cpp

namespace file2
{
     ...
     ...
}

How will I link file1.cpp with file2.cpp? It throws error that file1.cpp can't find file2 namespace . I tried adding namespace file2{} in file1.cpp, but still the same error.

You'll need a header to declare things that are to be accessed from more than one source file:

// file2.h
#pragma once  // or a traditional include guard if you prefer

namespace file2 {
    void func();
}

Now include this from file1.cpp to enable the use of file2::func from there.

// file1.cpp
#include "file1.h"

// ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM