Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to compile and run a single .cpp file in a Visual Studio Express '12 project?

I have just started learning c++ and I am using Microsoft Visual Studio Express 2012. I started a project where I was planning to have all my .cpp files but I have now run into a problem where when I try to compile and run a specific .cpp file it doesn't work.

VS seems to just compile and run the .cpp file with the main function in it and it makes a .exe and runs it. So since my first .cpp file (that holds the main()) is a simple hello world program I am only getting that one when I try to compile and run now.

I have another .cpp file with a int age() function that is supposed to ask for a users age and then output it. It's very simple and I just want to run it to see it in action but I can't figure out how to compile that particular .cpp file in my project since it only seems to want to compile the main .cpp file with the main() function.

How can I compile a specific .cpp in the project?

like image 366
Zbl Avatar asked Oct 22 '22 05:10

Zbl


2 Answers

All c++ programs start in the main function. Why don't you try calling age() from main?

Of course, in order to do so, you will need your main.cpp to be aware that there is a function called age. This is where header files come in.

In total, you will therefore need the following:

main.cpp

#include "age.h"

int main() {
    age();
    return 0;
}

age.h

#ifndef AGE_H
#define AGE_H

int age();

#endif

age.cpp

#include "age.h"

int age() {
    // Do age stuff.
    return 42;
}
like image 108
zennehoy Avatar answered Oct 24 '22 11:10

zennehoy


Try dividing your .cpp files into Projects if you really have to compile them separately. but for that too you will need a main in each of the projects.

Another choice you have is creating dll projects. But since you told you want to keep it simple i wont suggest it.

For too simple console programs use some more easier & simpler IDEs. But what ever be the IDE, ccp files (even c) programs can be run only from main.

like image 26
Rohit Vipin Mathews Avatar answered Oct 24 '22 13:10

Rohit Vipin Mathews