0

I'm very new at C++: I'd like to put part of the source code in to another source file and be able to execute the source of the second file by calling it out from the first file, is this even possible? I appreciate some guidance.

The following sample program output an X to a random location at the Linux console.

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <chrono> //slow down
#include <thread> //slow down
using namespace std;

void gotoxy(int x,int y)       
{
    printf("%c[%d;%df",0x1B,y,x);
}

int main()                     
{
    int x=1;
    int y=1;
    int b=1;
    for (;;) { // I'd Like this Loop execution in a separate source File
        gotoxy (1,40);               
        cout << "X =" <<x <<endl;      
        cout << "Y =" <<y <<endl;      
        x = rand() % 30 + 1;           
        y = rand() % 30 + 1;            
        for (int b=0 ;b<10000;b=++b){  
            gotoxy (x,y);
            cout << " X ";
            cout <<"\b \b"; // Deletes Just Printed "X"
        }
    }
}
cbuchart
  • 10,847
  • 9
  • 53
  • 93
  • 2
    To answer the question that you asked: yes, it is possible, and as far as "some guidance" goes, [you will find plenty of guidance in this link](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Sam Varshavchik Mar 21 '17 at 21:28

2 Answers2

5

You will need two more files, one header file and one source file. In the first you will declare a function, while in the other you will define it.

For example you could do this:

Header file: myFunc.h

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <chrono>
#include <thread>

using namespace std;

void myLoop(int x, int y);

Source file: myFunc.cpp

#include "myFunc.h"

void gotoxy(int x,int y)       
{
  printf("%c[%d;%df",0x1B,y,x);
}

void myLoop(int x, int y)
{
  for (;;) {  
    gotoxy (1,40);                 
    cout << "X =" <<x <<endl;      
    cout << "Y =" <<y <<endl;      
    x = rand() % 30 + 1;           
    y = rand() % 30 +1;            
    for (int b=0 ;b<10000;b=++b){  
      gotoxy (x,y);
      cout << " X ";
      cout <<"\b \b";
    }
  }
}

And then in main source file, you would do:

#include "myFunc.h"

int main()                     
{
  int x=1;
  int y=1;
  myLoop(x, y);
  return 0;
}

Compile it like this:

g++ -Wall myFunc.cpp main.cpp -o main

gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

C++ is highly designed to separate code into many files in order to allow us to organize code. First you need to put code into a function. Then put that function in a separate file. You will need both a .h header file and a .cpp file with the code.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268