Why does C allow me to call an undeclared function? [duplicate] - c++

This question already has answers here:
Why the error of - calling the function before being declared, is not shown?
(3 answers)
Closed 4 years ago.
I have two files: test1.c, and test2.c, which contains the main() function.
test1.c:
#include <stdio.h> // printf() function declaration/prototype
// function definition
void say_hello() {
printf("\tHello, world!\n");
}
test2.c:
#include <stdio.h> // printf() function declaration/prototype
int main() {
printf("Inside main()\n");
say_hello();
return 0;
}
And this is my makefile:
a.out: test1.o test2.o
$(CXX) -o a.out test1.o test2.o
test1.o: test1.c
$(CXX) -c test1.c
test2.o: test2.c
$(CXX) -c test2.c
Now it should be clear where the problem lies: The main() function in test2.c calls say_hello() without declaring it!
I run the following command, to use the gcc compiler:
make CXX=gcc
I get this warning to the screen:
gcc -c test1.c
gcc -c test2.c
test2.c: In function ‘main’:
test2.c:16:3: warning: implicit declaration of function ‘say_hello’ [-Wimplicit-function-declaration]
say_hello();
^
gcc -o a.out test1.o test2.o
Although the *.o files got compiled and linked into the executable. That's weird. Imagine my surprise when I run the a.out file, and I see that main() successfully called say_hello(), a function which is not declared inside of main's translation unit, as if there were no issue at all! I reason that since say_hello() was not previously declared in test2.c, it should not allowed to be called by main() at all. Notice that I've added comments to the #include <stdio.h>. These preprocessor directives include the function declarations/prototypes, which extend their scope into the corresponding *.c files. That is why we are able to use them. No function declaration/prototype == no scope in that translation unit, or so I thought until now.
Then I compiled the above code as C++ code:
make CXX=g++
I get this error to the screen:
test2.c: In function ‘int main()’:
test2.c:16:13: error: ‘say_hello’ was not declared in this scope
say_hello();
^
makefile:18: recipe for target 'test2.o' failed
make: *** [test2.o] Error 1
g++ does what it's supposed to do, and stops the compilation process. But gcc did not do this! What's going on? Is it a perk of the C programming language? Is it an issue with the compiler?

Simple, because C allows undeclared functions to be called and C++ does not. Either way, gcc warns you and you may want to take warnings seriously.

Related

Including files correctly , but still getting linker error

hope you guys are doing well. I am just getting linker error in C++ , I don't know why? Everything is correct....
Check below testing.h file
#ifndef __MYClass__
#define __MYClass__
#include<iostream>
using namespace std;
class Abc {
private:
int a;
public:
void input();
void display();
};
#endif
and here's implementation of these functions in Functions.cpp file.
#include"testing.h"
void Abc::input() {
cout<<"Enter any value : ";
cin>>a;
}
void Abc::display() {
cout<<"You Entered : "<<a;
}
And now, in main.cpp
#include<iostream>
#include"testing.h"
using namespace std;
int main() {
Abc obj;
obj.input();
obj.display();
return 0;
}
All files are compiled successfully.
In main.cpp Linker says....
g++ -Wall -o "main" "main.cpp" (in directory: /home/Welcome/C++ Practices/testingLinux)
/usr/bin/ld: /tmp/ccYI9LAy.o: in function main': main.cpp:(.text+0x10): undefined reference to Abc::input()'
/usr/bin/ld: main.cpp:(.text+0x1c): undefined reference to `Abc::display()'
collect2: error: ld returned 1 exit status
Compilation failed.
I'm using built-in linux compiler...
There are multiple ways you can fix this but before that please read up on Translation Unit.
Coming to your problem.
When you write
g++ -Wall -o main main.cpp
The compiler will pick up main.cpp for compilation and expand testing.h that includes the declaration for class ABC and with this header file it can determine what is the size of ABC and be able to generate instructions reserving space for obj on the stack. It can't see the definition for input() and display() hence defers that task to the linker. Note that testing.cpp is not in the picture at all since the compiler doesn't know that the implementation of ABC is in testing.cpp. Now when the linker tries to resolve the symbols input() it fails to find the definition for it and throws the error
undefined reference to Abc::input()
So, to fix this you can tell explicitly upfront that it also needs to take in testing.cpp while compiling main.cpp by
g++ -o main main.cpp testing.cpp
Another way is to create a dynamic library out of testing.h and testing.cpp
g++ -shared -fPIC testing.cpp -o libtest
and then link it against main.cpp
g++ -o main main.cpp -I. -L. libtest
What this does is that the compiler still can't figure out the definition of input() and display() but the linker can since now the library containing the definitions is provided to it.
You are not compiling Functions.cpp file.
This should fix your issue:
g++ main.cpp Functions.cpp

g++ undefined reference to constructor , really simple code

I made a program to test my knowledge on class but I had some troubles.
foo.h:
#include <iostream>
using namespace std;
class foo
{
private:
int a;
public:
foo();
};
foo.cc:
#include <iostream>
#include "foo.h"
using namespace std;
foo::foo()
{
a = 0;
}
And main.cc:
#include<iostream>
#include "foo.h"
int main()
{
foo a;
return 0;
}
I compiled this with g++ main.cc -o main. Then I got
-bash-4.1$ g++ main.cc -o main
/tmp/cc5Hnes8.o: In function `main':
main.cc:(.text+0x10): undefined reference to `foo::foo()'
collect2: ld returned 1 exit status
I think there should be a really stupid mistake here but I really cannot find it. I've been struggling on this whole night...
Appreciate any help!
You are asking the compiler to not only translate main.cc but also perform the final link to produce the executable main. This second step cannot be done because main.cc references the function foo::foo whose definition is in foo.cc and therefore not available to the compiler. You can do this:
g++ main.cc -c -o main.o
g++ foo.cc -c -o foo.o
g++ main.o foo.o -o main
The -c flag makes the compiler perform translation only, so this separately compiles main.cc and foo.cc and then links the objects together to obtain the executable. In this way, the definition of foo::foo will end up inside foo.o and will be available at link time.
Or, you can just provide both .cc files. This basically does the same thing as the three commands above:
g++ main.cc foo.cc -o main
You should compile all source (.cc in your case) files:
g++ main.cc foo.cc -o main
When you realize the constructor of foo in foo.cc, you should compile it.
use g++ main.cc foo.cc -o main.

Undefined reference to function from a different header file c++ [duplicate]

This question already has answers here:
Linking files in g++
(4 answers)
Why can templates only be implemented in the header file?
(17 answers)
Closed 8 years ago.
I am simply trying to use a function whose prototype is declared in a separate header file (ML_hash.h) and whose declaration is made in separate cpp file. I am trying to call this function in a different header file (HashNode.h). Here is the relevant code:
HashNode.h:
#ifndef HASHNODE_H
#define HASHNODE_H
#include "ML_hash.h"
template < typename T >
class HashNode
{
... // function prototype declarations
};
template< typename T >
void HashNode< T >::insert(int key, T* object)
{
...
int retVal = ML_hash(1, 3);
...
}
...
#endif
ML_hash.h:
#ifndef INC_ML_HASH
#define INC_ML_HASH
int ML_hash(int level, int key );
#endif
The error I am getting is:
g++ -o hash Hashtest.o:
Hashtest.o: In function `HashNode<int>::insert(int, int*)':
/home/adalal1/programs/class/final_project/HashNode.h:72: undefined reference to ' ML_hash(int, int)'
/home/adalal1/programs/class/final_project/HashNode.h:88: undefined reference to ` ML_hash(int, int)'
Hashtest.o: In function `HashNode<int>::explode()':
/home/adalal1/programs/class/final_project/HashNode.h:117: undefined reference to ` ML_hash(int, int)'
collect2: error: ld returned 1 exit status
What I don't understand is why the C++ compiler doesn't recognize the ML_hash function defined in ML_hash.cpp. I did include ML_hash.h in that cpp file. Could anyone provide insight into why this is happening?
EDIT:
I compile the code with a Makefile shown below:
C++ = g++
CFLAGS = -c -g
all: hash
hash: Hashtest.o
$(C++) -o hash Hashtest.o
clean:
rm -f *.o
%.o: %.cpp
$(C++) $(CFLAGS) $*.cpp
'ld returned 1 exit status' -> this is a linker error, not a compiler error.
Looks like you are running into this issue:
Linking files in g++
EDIT:
Either
g++ -o hash ML_hash.cpp HashNode.cpp HashTest.cpp
or
g++ -c ML_hash.cpp
g++ -c HashNode.cpp
g++ -c HashTest.cpp
g++ -o hash ML_hash.o HashNode.o HashTest.o
EDIT2 with OP edit:
I'm no makefile expert, but it looks like the 'hash:' target is just missing ML_hash.o and HashNode.cpp
hash: HashNode.o
ML_hash.o
Hashtest.o
$(C++) -o hash Hashtest.o ML_hash.o HashNode.o

Force compile error in G++ for undeclared functions

I've installed GCC 4.8 using this method on my Mac. Everything works fine except that for certain functions like scanf and printf, the program compiles fine without any error/warning even when I did not include their respective libraries like cstdio. Is there any way that I can do to for GCC (more specifically G++, as I am dealing with C++ programs) to throw an error when such code is being fed? The following code compiles fine on my machine:
#include <iostream>
//Notice I did not include cstdio but my program uses printf later on
int main()
{
printf("Hello World!\n");
return 0;
}
I was given the suggestion to use -Werror-implicit-function-declaration -Werror or -Wall -Werror, but they don't work.
-Wimplicit-function-declaration -Werror works for me. There must be some other problems as well.
h2co3-macbook:~ h2co3$ cat baz.c
#ifndef BAILZ_OUT
#include <stdio.h>
#endif
int main()
{
printf("Hello world!\n");
return 0;
}
h2co3-macbook:~ h2co3$ gcc -o baz baz.c -Wimplicit-function-declaration -Werror
h2co3-macbook:~ h2co3$ echo $?
0
h2co3-macbook:~ h2co3$ gcc -o baz baz.c -Wimplicit-function-declaration -Werror -DBAILZ_OUT
cc1: warnings being treated as errors
baz.c: In function ‘main’:
baz.c:7: warning: implicit declaration of function ‘printf’
baz.c:7: warning: incompatible implicit declaration of built-in function ‘printf’
h2co3-macbook:~ h2co3$ echo $?
1
h2co3-macbook:~ h2co3$
The reason you get no diagnostic is that <iostream> is including the declaration of printf, which it seems to do with the c++0x or c++11 flags.
This compiles on a gcc 4.8 snapshot with the following command line:
g++ -Wall -Wextra -pedantic-errors -std=c++0x
#include <iostream>
int main()
{
printf("Hello World!\n");
return 0;
}
If you comment out the <iostream> include, or remove the C++11 compilation flags, you get an error.
impl_decl.cpp: In function 'int main()':
impl_decl.cpp:5:28: error: 'printf' was not declared in this scope
From the Annex C/Compatibility of the C++ standard from 2003:
C.1 C++ and ISO C:
C.1.3 Clause 5: expressions [diff.expr]
5.2.2
Change: Implicit declaration of functions is not allowed
Rationale: The type-safe nature of C++.
That means that implicit declarations must cause a compilation error in C++.
I'm guessing you're compiling not C++ files, but C files and you're doing that in some pre-C99 mode, which is the default in gcc. The C standard from 1999 disallows implicit declarations as well.
You may want to pass to gcc a combination of these options: -std=c99 -Werror.

Forcing GCC 4.x to treat -Wreturn-type as an error without enabling -Werror?

Suppose we have the following code:
#if !defined(__cplusplus)
# error This file should be compiled as C++
#endif
#include <stdio.h>
#include <string>
//#define USE_CXX_CLASS
#ifdef USE_CXX_CLASS
class SomeClass
{
public:
SomeClass() {}
~SomeClass() {}
std::string GetSomeString()
{
// case #1
}
};
#endif // USE_CXX_CLASS
int foo()
{
// case #2
}
int
main (int argc, char *argv[])
{
(void)argc;
(void)argv;
#ifdef USE_CXX_CLASS
SomeClass someInstance;
someInstance.GetSomeString();
#endif // USE_CXX_CLASS
foo();
return 0;
}
And suppose that it were to be compiled the C++ compiler (and not the C compiler) from GCC version 4.2.1 with the options -Wreturn-type -Werror=return-type. If the above code is compiled as is without first uncommenting the //#define USE_CXX_CLASS line above, then you will see a warning but no error:
.../gcc-4.2.1/bin/g++ -g -fPIC -Wreturn-type -Werror=return-type test.cpp -c -o test.o
test.cpp: In function 'int foo()':
test.cpp:26: warning: control reaches end of non-void function
But if the //#define USE_CXX_CLASS line is uncommented, then the warning is treated as an error:
.../gcc-4.2.1/bin/g++ -g -fPIC -Wreturn-type -Werror=return-type test.cpp -c -o test.o
test.cpp: In member function 'std::string SomeClass::GetSomeString()':
test.cpp:18: error: no return statement in function returning non-void [-Wreturn-type]
gmake: *** [test.o] Error 1
Yes, one is a non-member function (case #2), and the other is a C++ function (case #1). IMO, that should not matter. I want both conditions treated as an error, and I don't want to add -Werror or -Wall at this point in time (probably will do so later, but that is out of scope of this question).
My sub-questions are:
Is there some GCC switch that I am missing that should work? (No I do not want to use #pragma's.)
Is this a bug that has been addressed in a more recent version of GCC?
For reference, I have already poured through other similar questions already, including the following:
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
C question: no warning?
Is a return statement mandatory for C++ functions that do not return void?
It has been fixed, it works well with g++ 9.3: both member functions and free functions are treated as error with -Wall -Werror=return-type
I do see an error even w/o the USE_CXX_CLASS flag. i.e. g++ is consistent with the error for both class member functions and non member functions.
g++ (GCC) 4.4.3 20100127 (Red Hat 4.4.3-4)
It seems to me that what you need is a shell script wrapper around gcc.
Name it something like gcc-wrapper and g++-wrapper.
In your Makefile set CC and CXX to the wrappers.
Have the wrapper invoke GCC and pipe its output to another program which will search for your desired warning strings.
Have the search program exit with an error when it finds the warning.