C ++ - 在另一个文件中使用.cpp文件?

时间:2014-04-15 14:39:19

标签: c++ methods

只是一个简单的问题:是否可以在另一个.cpp文件中使用.cpp文件 - 就像调用它一样。

E.g。 File1.cpp:

#include < iostream > 
#include < string >
  using namespace std;

void method(string s);

int main()
{
  method("Hello World");
  return 0;
}

void method(string s)
{
  //get this contents from file2.cpp
}

和File2.cpp:

#include <iostream>

using namespace std;

void method(string s)
{
   cout << s << endl;
}

所以能够做到这一点。 所以我不把所有代码都填入1 cpp文件

感谢。

2 个答案:

答案 0 :(得分:2)

你需要制作一个头文件;例如File2.h,在其中为每个要重用的函数放置原型:

#ifndef FILE2_H_
#define FILE2_H_    

void method(string s);

#endif  /* FILE2_H_ */

然后您需要在File2.cpp和File1.cpp中包含此标头:

#include "File2.h"

现在在File1.cpp中你可以调用这个函数而不用声明它:

int main()
{
  method("Hello World");
  return 0;
}

答案 1 :(得分:0)

我这样做: File2.h:

#ifndef __File2_H__
#define __File2_H__

// Define File2's functions...
void method(string s);

#endif

File2.cpp:

#include "File2.h"
// implement them....
void method(string s)
{
    cout << s << endl;
}

File1.cpp

// This include line makes File1.cpp aware of File2's functions
#include "File2.h" 
// and now you can use File2's methods inside method() below.
void method()
{
    method(string("I am batman"));
}

然后将它们链接为@chris说(以下是shell脚本/命令):

# Compile them first
cc -o file1.o File1.cpp
cc -o file2.o File2.cpp
# Then link them
cc -o program file1.o file2.o