forward declaration

Hello

im new to programming and im trying use forward declaration to access some functions from main


//main.cpp

 
#include <stdlib.h>

int readNumber();
void
writeAnswer(int);
int
main() {
    int a = readNumber();
    int
b = readNumber();
    
writeAnswer(a+b);

    
system("Pause");
    return 0;
}



//io.cpp

 
#include <iostream>

int readNumber()
{
    using namespace std;
    
cout<<"enter a number:\n";
    int
x;
    
cin>>x;

    return
x;
}
void writeAnswer(int z)
{
    using namespace std;
    
cout<<"Your answer is "<<z<<endl;
}


the file is in the solution explorer. How would i check the properties in clion i can not find it. i know visual studios you need to add a preprocessor in order to compile and link properly.

2 comments
Comment actions Permalink

Hi Kevin.

To Run your project in CLion please check the following:
You have two separate files main.cpp and io.cpp
All project files are not greyed out in the project hierarchy
There are not highlighted code in the project
Executable field isn’t empty (Run | Edit Configurations - Executable)

0
Comment actions Permalink

Hey Kevin,

Doing a few things wrong here.  What you want to do for declarations is put them in their own header.  Doing forward declarations in main.cpp is more used when the functions follow later in the file.  It lets the file know about int readNumber() before the implementation so you can use it before the implementation is written in the cpp file.

Here is what you want to do:

// main.cpp
#include <stdlib.h>
#include "io.h"

int main()
{
   int a = readNumber();
   int b = readNumber();
   writeAnswer(a+b);
   return 0;
}

// io.h

#ifndef __io_H
#define __io_H

// the above is header protection so things aren't defined multiple times.  All C++ headers should use it.

int readNumber();
void writeAnswer(int);

#endif // __io_H

// io.cpp

#include "io.h"
#include <iostream>

using namespace std;

int readNumber()
{
   cout << "enter a number:" << endl;
   int x;
   cin >> x;
   return x;
}

void writeAnswer(int z)
{
   cout << "Your answer is " << z << endl;
}

Hope that helps. :)

0

Please sign in to leave a comment.