I am writing a program split in three different files:
1) An header named my.h;
A source cpp file named my.cpp;
The main file named use.cpp;
Here their statements:
/* Header file my.h
Define global variable foo and functions print and print_foo
to print results out */
extern int foo;
void print_foo();
void print(int);
/* Source file my.cpp where are defined the two funcionts print_foo() and print()
and in where it is called the library std_lib_facilities.h */
#include "stdafx.h"
#include "std_lib_facilities.h"
#include "my.h"
void print_foo() {
cout << "The value of foo is: " << foo << endl;
return;
}
void print(int i) {
cout << "The value of i is: " << i << endl;
return;
}
/ use.cpp : definisce il punto di ingresso dell'applicazione console.
//
#include "stdafx.h"
#include "my.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int foo = 7;
int& i = foo;
i = 99;
char cc = '0';
while (cin >> cc) {
switch (cc) {
case '1':
void print_foo();
break;
case '2':
void print();
break;
default:
exit(EXIT_FAILURE);
}
}
return 0;
}
My main problem is that program compiles and run correctly but it doesn't print anything as I supposed.
How can I fix it?
Thank you!
Leo
To call a function specifying return type is not required. Correct
void print_foo(); // This actually declares a function prototype
to
print_foo();
and
print(i); // Pass i as argument
Drop the void from void print_foo(); and void print(); in the switch blocks.
Currently you're just declaring a function prototype; not actually calling the function.
Your extern int foo; approach, while syntactically valid, can make your codebase harder to scale and maintain: consider passing the parameter explicitly.
Your code claims to *"Define global variable foo..." as follows...
extern int foo;
...but that just declares that some translation unit will actually define it (without the leading extern qualifier). There's no actual variable in the code you've posted, which means your program shouldn't link unless some library you're using coincidentally has a foo symbol in it.
This shorter code condenses your problem:
#include <iostream>
extern int foo;
void f()
{
std::cout << foo << '\n';
}
int main() {
int foo = 7;
f();
}
You can see the compiler error message here, namely:
/tmp/ccZeGqgN.o: In function `f()':
main.cpp:(.text+0x6): undefined reference to `foo'
collect2: error: ld returned 1 exit status
You would put in the main function
case '1':
print_foo();
break;
Notice I erased the word "void" in the case 1. Because you don't redeclare the function there. You just use it.
Related
I know what "forward function declaration" means, but I want get the same with variables.
I have this code snippet:
#include <iostream>
int x;
int main()
{
std::cout << x << std::endl; // I want get printed "2" but I get compile error
return 0;
}
**x = 2;**
In the std::cout I want print "2" value, but trying to compile this I get this compile error: error: 'x' does not name a type.
While this doesn't appear somthing of programmatically impossible, I can't compile successfully.
So what is the right form to write this and obtain a forward variable declaration?
Variable declarations need extern. Variable definitions need the type, like declarations. Example:
#include <iostream>
extern int x;
int main()
{
std::cout << x << '\n';
}
int x = 2;
Normally you'd use extern to access a variable from a different translation unit (i.e. from a different .cpp file), so this is mostly an artifical example.
You can declare
extern int x;
in this file, and in some other file
int x = 2;
You could use Class and declare variable inside. Also, anonymous namespace is needed as Vlad said. Example:
#include<iostream>
namespace
{
class MyClass
{
public:
static int x;
};
}
int main()
{
std::cout << MyClass::x;
}
int MyClass::x = 2;
I am learning C++ on a linux machine. I just tried “int i();” to declare a function but I forgot to define it. But to my surprise, this code can be compiled and output 1. I feel very confused. I tried “int I{};”, it still compiled with no errors. Please help to explain. Thanks in advance.
//test1.cpp
#include <iostream>
int main(void)
{
int i{};
std::cout << i << std::endl;
return 0;
}
g++ test1.cpp
./a.out
Output is: 0
//test2.cpp
#include <iostream>
int main(void)
{
int i();
std::cout << i << std::endl;
return 0;
}
g++ test2.cpp
./a.out
Output is : 1
In your first example, you define a variable named i, and value-initialise it, which for int means zero-initialisation.
int i{}; // defines i, initialised to zero
In your second example, you declare a function named i, which takes no parameters, and return int:
int i(); // declares a function
When you print this:
std::cout << i << std::endl;
i first get converted to bool (i decays to a function non-nullptr pointer, then it becomes true), and then printed as an integer, that's why you get 1. The compiler can make this conversion without the definition of i (as the result is always true), that's why you got no linker error.
If your intent was to call this function, and print the result, you'll need to use i():
std::cout << i() << std::endl;
This, of course, needs i's definition.
In your code:
//test1.cpp
#include <iostream>
int main(void)
{
int i{};
std::cout << i << std::endl;
return 0;
}
You are not actually declaring a function without defining it. The line of code int i{}; within the main() function here is a variable of type int named i and you are using a brace initializer list to initialize the variable i with out any values and in most cases could be 0 but can vary by compiler.
//test2.cpp
#include <iostream>
int main(void)
{
int i();
std::cout << i << std::endl;
return 0;
}
In this situation it is basically the same thing. You are within main() and by the rules of the language "you can not declare-define a function within a function", so this results in a declaration - definition of a variable. The only difference here is you are not using a brace initializer list here you are using it's ctor constructor called value initialization. Again you are not passing any values to it and in your case it's assigning an arbitrary value of 1.
Now if your code looked like this:
#include <iostream>
int i();
int main() {
std::cout << i() << '\n';
return 0;
}
This would fail to compile because the function i is declared but not defined. However if you did this:
#include <iostream>
// The text in quotes is not meant to be a string literal. It
// is the message of the text that represents any integer X.
int i() { return /*"some int value"*/ 1; }
int main() {
std::cout << i() << '\n';
return 0;
}
This would compile and run perfectly fine because the function i is both declared and defined.
This is my A.h file
class A
{
public:
void menuChoice();
void displaystartingMenu(); //EDIT
};
This is my A.cpp file
#include "A.h"
void displaystartingMenu()
{
cout<<"Please enter your choice:";
}
void A::menuChoice()
{
displaystartingMenu();
cout<<"Hello"<<endl;
}
int main()
{
A a;
a.menuChoice();
}
i tried to put
void menuChoice();
on the top of my cpp file but it still won't compile . it gives me error
In function ‘int main()’: A.cpp:112:13: error: ‘menuChoice’ was not declared in this scope menuChoice();
How do I compile : g++ A.cpp A.h
By right I don't need to even declare the function of top of the cpp because I have already declare it in my header file and I have included in my .cpp. What went wrong here?
EDIT:
Error :
In function `A::menuChoice()':
A.cpp:(.text+0x229): undefined reference to `A::displaystartingMenu()'
Option 1: Make an A instance and call that instance's menuChoice method:
#include <iostream>
class A {
public:
void menuChoice();
};
void A::menuChoice() {
std::cout << "Hello" << std::endl;
}
int main() {
A a;
a.menuChoice();
return 0;
}
Option 2: Make menuChoice a static method and call it as A::menuChoice:
#include <iostream>
class A {
public:
static void menuChoice();
};
void A::menuChoice() {
std::cout << "Hello" << std::endl;
}
int main() {
A::menuChoice();
return 0;
}
Edit: Addressing the new problem, when you tried to define A::displaystartingMenu you wrote:
void displaystartingMenu() {
// ...
}
It must be defined like this:
void A::displaystartingMenu() {
// ...
}
menuChoice is a non static member function of class A. In order to call it you need to instantiate an object A, as follows
int main()
{
A a;
a.menuChoice();
return 0;
}
Hey guys I'm trying to learn C++ and I was doing pretty well until I hit this wall..
I am getting two errors:
error: 'enter' was not declared in this scope
error: 'Satisfies' was not declared in this scope|
Here is my file. Why is that?
include <iostream>
using namespace std;
int main() {
while (1){
char menu;
cin>>menu;
switch (menu){
case 1: Enter(); break;
case 2: Satisfies(); break;
case 3: break;
};
};
}
int Enter(){
return 0;
}
int Satisfies(){
return 0;
}
You have to declare the functions before their usage for example before main and use the correct syntax of calling functions.
For example
//...
int Enter(){ return 0; }
int Satisfies(){ return 0; }
//...
int main()
{
//...
case 1:
Enter();
//...
You need to declare the functions before they are used. So put this above main:
int Enter();
int Satisfies();
You can leave the definitions (the bit that actually contains the code to run when the function is called) where they are. Or you can just move those functions above main, since a function definition is also a declaration.
The compiler needs to see these bits before it tries to call the function, so that it can know what arguments it needs, and what will be returned.
See this question.
You need to declare (or declare and definite) a function before you use it. And you need to make function calls with (). Like Enter() and Satisfied(). If you want to learn good programming and C coding and then go to C++ read "C for Dummies" by Dan Godkin. My favourite coding book.
You have 3 ways to do this and fix your code:
1. Write prototy definitions:
#include <iostram>
int Enter();
int Satisfies();
using namespace std;
int main()
{
//bla
}
int Enter(){ return 0; }
int Satisfies(){ return 0; }
2. Make a function.h file and put the declarations there. Save it in the same folder as the c / cpp file
then include in your code
#include "function.h"
3 Put your functions in order of execution in the c/cpp file. A function must be declared before it is used. Example:
void Enter()
{
//bla
}
void Satisfied()
{
//blub
}
int main()
{
Enter();
Satisfied();
}
More tricky example, when a function (Satisfied) uses an other function (Enter) the Enter function must be declared before the Satisfied function:
void Enter()
{
//bla
}
void Satisfied()
{
//blubb
Enter(); //now Enter must be declared before is Satisfied() is defined, so it must be "over" it in the source like in this example
}
int main()
{
Enter();
Satisfied();
}
Function call need to have () after the function name doesn't matter whether it take any parameter or not. Plus you need to define function header before main()
include <iostream>
using namespace std;
int Enter();
int Satisfies();
int main() {
while (1){
char menu;
cin>>menu;
switch (menu){
case 1: Enter();
break;
case 2: Satisfies();
break;
case 3:
break;
};
};
}
int Enter(){
return 0;
}
int Satisfies(){
return 0;
}
What's the point of initialising an unnamed C++ parameter? For example:
void foo(int = 0) {}
A declaration has no need of a parameter name. The definition does, however. Also, the default parameter cannot be repeated in the definition. Here's a small program that works (but I don't know why you would want to do something like this, really...):
#include <iostream>
void foo(int = 5);
int main() {
foo();
foo(3);
return 0;
}
void foo(int i) {
std::cout << i << std::endl;
}
The output is
5
3
I can imagine in the context of callback functions the construct might be useful:
#include <iostream>
// Please assume the callback is an external library:
typedef void (*callback_function)(int);
callback_function callback;
void foo(int = 0) {
std::cout << "Hello\n";
}
int main() {
callback = foo;
callback(1);
foo();
}
It will serve as the default parameter value. It belongs in the function declaration.