简体   繁体   中英

C++ - Using a .cpp file in another?

just a simple question: Is it possible to use a .cpp file in another .cpp file - Like calling for it.

Eg 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
}

and File2.cpp:

#include <iostream>

using namespace std;

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

So to be able to do something along the lines of that. So I dont stuff all my code into 1 cpp file

Thanks.

you need to make a header file; eg File2.h, in which you put the prototype for each of the functions you want to reuse:

#ifndef FILE2_H_
#define FILE2_H_    

void method(string s);

#endif  /* FILE2_H_ */

then you need to include this header both in File2.cpp and File1.cpp:

#include "File2.h"

now in File1.cpp you can just call this function without declaring it:

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

I'd do it like this: 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"));
}

Then link them as @chris said (the following is shell script/commands):

# 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

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