1

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

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
}

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.

4
  • 3
    Yes, you have to link them. Normally, you'd include a header that declares method instead of doing it yourself. Commented Apr 15, 2014 at 14:40
  • @chris: not sure I follow u. Commented Apr 15, 2014 at 14:43
  • 2
    This is about the real basics: .h and .cpp files and linking. I think you should pick up a book or read a beginners tutorial. To answer the question, you can #include 'file2.cpp', but this is not standard practice. Commented Apr 15, 2014 at 14:43
  • TYpically, you'd want either to not implement method(string s) in file1.cpp for this to work. Or have a different name for method - as the compiler can't tell the two functions apart as it stands. Commented Apr 15, 2014 at 14:44

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

No discussion of header file?
indeed, this might work, but it is quite dirty in my opinion... header files are the way to go...
Granted, header files are smarter. I'll edit the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.