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?
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With