GnomeSort
GnomeSort

Reputation: 285

Function included in header not executing, but no compile errors

I have a simple main function that calls another which is included in a header.

As you can see, the main function includes main.h, as does initvars.cpp. I expect my function, when executed, to call the function initvars, which should print to the command window "Hello world" and then wait for user input to close the window.

However, I am not getting this result - when I run 'debug' in VS 2015, the command window opens and then closes immediately.

Why does this code fail to elicit the desired response?

//Source.cpp

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

void main() {
    void initVars();
}


//main.h

void initvars() {
std::cout << "Hello world" << std::endl;
std::cin.get();
}


//initvars.cpp

#ifndef _MAIN_H
#define _MAIN_H
#include <string>

void initVars();

#endif

Upvotes: 0

Views: 57

Answers (2)

Brett
Brett

Reputation: 897

Your code is failing to compile but running the last successfully compiled version.

Change

void main() {
    void initVars();
}

to

void main() {
    initVars();
}

I'd also recommend following this answer so that you'll be alerted to your code failing to compile more explicitly.

Upvotes: 0

Ghooo
Ghooo

Reputation: 496

if you want to call a function, you do so by its name only without the type which is void here:

void main() {
  initVars();
}

as for why there is no compilation error, this is because the compiler considers

void initVars();

inside the main as a prototype to the function, and yes prototype can be inside functions not only in the global scope, that is why there is no errors.

as for the naming it is better to call the file containing the main function something like main.cpp and the files containing classes as classname.h and classname.cpp . Also note that you need to include the header file of your class into your cpp file.

Upvotes: 3

Related Questions