@kytcenochka

Связь между cpp файлами? Как можно получить и записать значение переменной из одного cpp в другой?

Делаю два сpp файла, чтобы собрать из них библиотеку с помощью makefile в LINUX
Мне нужно записать значения переменных discretX, discretY из function1.cpp в function2.cpp
Как это сделать?

function.h
struct InfaboutChanell
{ 
    int chanellcount;
    int analogChanell;
    int discretChanell;
};
void writeCfgFile (); 
void writeBinaryFile();


function1.cpp
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include "functions.h"
using namespace std;


 struct Station station;
   void writeCfgFile(){

        ofstream file("fileConfiguration.cfg");
       //The information about count of channels
       struct InfaboutChanell infaboutChanell;
       infaboutChanell.chanellcount=14;
       const int analogX =6;
       infaboutChanell.analogChanell=analogX;
       const int discretX=8;
       infaboutChanell.discretChanell=discretX;  
       //проверка на сумму каналов
       int sum;
       sum = infaboutChanell.analogChanell+infaboutChanell.discretChanell;
       if (sum != infaboutChanell.chanellcount)
       {
           cout << "Please enter correct count of channels: " <<'\n'; 
       }
       file<<infaboutChanell.chanellcount<<","<<infaboutChanell.analogChanell<<"A"<<","<<infaboutChanell.discretChanell<<"D"<<"\n";
      
       file.close();
   
}

function2.cpp
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include "functions.h"
using namespace std;

struct GeneralInf inf;
struct InfaboutChanell aboutchanell;


void writeBinaryFile(){
     // Create Binary file
    fstream binary_file("D:\\Struct\\Struct\\ComtradeFormat\\fileConfiguration.dat",ios::out|ios::binary|ios::app);
    if(!binary_file)
    {
        cout << "Cannot open file.\n";
        return 1;
    }

    int i=0;
    int n=0;
    int timestamp =0;

    for (i=0; i<=generalinformation.ensamp; i++){
        n = i+1;
        binary_file.write((char *) &n, sizeof n);
        timestamp = i*1000;
        binary_file.write((char *) &timestamp, sizeof timestamp);  

        // Value of analog channels
       short analogValue<b>  [analogX]</b>;
        for(int i=0; i<analogX; i++)
         
            analogValue[i] = rand() % 20000 - 10000;
        binary_file.write((char *) &analogValue, sizeof analogValue);

         unsigned __int16 m_bytesCount = 0;
         m_bytesCount = discretX / 16;
         if (discretX % 16){
             m_bytesCount++;
         }

        int ChValue<b> [discretX]</b> = {1, 1, 1, 0, 0, 0, 0, 0};
   
        for(int i = 0; i < discretX; ++i)
        {
            if(ChValue[i] == 1)
                m_bytesCount |= 1 << i;
        }

        binary_file.write((char *) &m_bytesCount, sizeof m_bytesCount);
    }

    binary_file.close();
  • Вопрос задан
  • 939 просмотров
Пригласить эксперта
Ответы на вопрос 4
Заведите глобалыне переменные в function.h файле и через них обменивайтесь данными в *.cpp файлах.
(так себе совет)
Ответ написан
Комментировать
@res2001
Developer, ex-admin
Возвращайте значения из одной функции и передавайте их в другую как параметры.
Вернуть 2 значения можно в структуре или с помощью входных параметров ссылок. Пример.
void writeCfgFile(int & directX, int & analogX){
       analogX =6;
       discretX=8;
}
void writeBinaryFile(int directX, int analogX) {
}
main() {
int analog, direct;
writeCfgFile(direct, analog);
writeBinaryFile(direct, analog);
}

Когда нужно возвращать много значений, то их объединяют в структуру и точно таким же образом заполняют структуру.
Глобальные переменные - это, конечно, просто и работает, но это не правильный подход.
Ответ написан
Комментировать
Punk_Joker
@Punk_Joker
Software Engineer в ВО Овен
В одном модуле глобальная переменная, и extern в другом.
Ответ написан
Комментировать
@Gytim
Ну можно указатель на объект передавать но так можно если везде его надо передавать и менять. А так set get свойства описывать.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы