I've been searching through questions on this for hours, and it just isn't working for some reason, so sorry if there's already an answer and I just didn't understand it.
I'm doing a course on C , and I've gotten to classes. As practice, he started by just calling a simple function that was defined in a separate .cpp file to show how a class would work later on. See code below:
//main.cpp
#include <iostream>
#include "Cat.h"
using namespace std;
int main() {
speak();
return 0;
}
============================
//Cat.cpp
#include <iostream>
#include "Cat.h"
using namespace std;
void speak() {
cout << "Meow" << endl;
}
================================
//Cat.h
#ifndef CAT_H_
#define CAT_H_
void speak();
#endif //CAT_H_
I've triple checked everything I could think of. They're in the same directory and I'm cross-referencing everything exactly as he did. I expect it to output "Meow" in the console, but if I call the speak() function in main.cpp, I still just get an empty function, despite it being defined in class.cpp. I don't know what I'm missing, and it's quite frustrating. Is is because of my compiler? I'm using Visual Studio IDE.
Edits: Used the wrong commented name
I'm using the built-in Visual Studio IDE's "Build" and "Compile" options. I'm not running the compilation using Linux commands or anything else.
@273K Here is the screenshot of my 3 VS files: https://i.stack.imgur.com/9tbw8.png
CodePudding user response:
The problem is that you are including Cat.h
but named your header class.h
instead of Cat.h
.
To solve this rename the files from class.h
and class.cpp
to Cat.h
and Cat.cpp
respectively, as shown below
Cat.h
#ifndef CAT_H_
#define CAT_H_
void speak();
#endif //CAT_H_
Cat.cpp
#include <iostream>
#include "Cat.h"
using namespace std;
void speak() {
cout << "Meow" << endl;
}
main.cpp
#include <iostream>
#include "Cat.h"
using namespace std;
int main() {
speak();
return 0;
}
CodePudding user response:
Thanks to @273K for the solution:
In the screenshot, the wrong project was "selected" in the solution explorer, so it was running the wrong project code.
I fixed it by right-clicking the project I wanted and clicking "Set as StartUp Project"