externint foo; Here you are declare that integer foo will appear somewhere in global scope, but there is no such integer defined anywhere in your program.
Documents/my.cpp:9:11: error: ISO C++ forbids declaration of ‘print_foo’ with no type [-fpermissive]
print_foo()
^
Documents/my.cpp: In function ‘int print_foo()’:
Documents/my.cpp:9:11: error: new declaration ‘int print_foo()’
Documents/my.h:7:6: error: ambiguates old declaration ‘void print_foo()’
^
Documents/my.cpp: At global scope:
Documents/my.cpp:19:12: error: ISO C++ forbids declaration of ‘print’ with no type [-fpermissive]
print(int i)
^
Documents/my.cpp: In function ‘int print(int)’:
Documents/my.cpp:19:12: error: new declaration ‘int print(int)’
Documents/my.h:8:6: error: ambiguates old declaration ‘void print(int)’
extern int foo;
^
cout<< " << foo << ";Prints string " << foo << " Do you see quotes? That everything between them is of another color (at least here, however your IDE should do this too). You are telling program to output strings. There is no variables involved.
class C {
public:
externint foo;
void print_foo();
void print(int);
};
I`m getting strange error:
Documents/my.cpp:9:6: error: ‘C’ has not been declared
void C::print_foo()
^
Documents/my.cpp:19:6: error: ‘C’ has not been declared
void C::print(int i)
I don`t understand them because I thought they were already included with my.h.
Look, if I add int foo; in my.cpp the output will be something like 0 and 99.
Foo is surely defined in "my.h" (see my earlier post) and is initialized to hold the value of 7.
I`m just doing what I was instructed to do in the exercise unless I have misunderstood the use of header files.
Foo is surely defined in "my.h" (see my earlier post) and is initialized to hold the value of 7.
Where? Content of your my.h as posted:
1 2 3
externint foo;
void print_foo();
void print(int);
There is no definition anywhere.
This:
1 2 3 4 5 6
int main()
{
int foo=7;
print_foo();
print(99);
}
Creates newlocal variable main::foo, print_foo() has no idea about.
If you are getting random values for foo, it means that you did not initialize it.
Either do int foo = 7; in my.cpp or foo = 7; in main before calling print_foo().
#include "my.h"
int main()
{
foo=7;
print_foo();
print(99);
}
Getting this:
g++ Documents/my.cpp Documents/use.cpp -o fast
/tmp/ccCagA8O.o: In function `print_foo()':
my.cpp:(.text+0x6): undefined reference to `foo'
/tmp/ccfjnp08.o: In function `main':
use.cpp:(.text+0x6): undefined reference to `foo'
collect2: error: ld returned 1 exit status
To elaborate - externint foo; doesn't actually define foo, or cause it to be instantiated. It just declares that foo is a global that's defined somewhere else.
If you don't actually define it somewhere else, then you get that linker error.