将 C++ 代码拆分为多个文件

0 c++ linux

我对 C++ 很陌生:我想将部分源代码放入另一个源文件中,并能够通过从第一个文件中调用它来执行第二个文件的源代码,这甚至可能吗?我感谢一些指导。

以下示例程序将 X 输出到 Linux 控制台的随机位置。

#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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

gsa*_*ras 5

您将需要另外两个文件,一个头文件和一个源文件。在第一个中,您将声明一个函数,而在另一个中,您将定义它。

例如你可以这样做:

头文件:myFunc.h

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

using namespace std;

void myLoop(int x, int y);
Run Code Online (Sandbox Code Playgroud)

源文件: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";
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在主源文件中,您将执行以下操作:

#include "myFunc.h"

int main()                     
{
  int x=1;
  int y=1;
  myLoop(x, y);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

像这样编译它:

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