This may happen because std::cout is writing to output buffer which is waiting to be flushed. If no flushing occurs nothing will print. So you may have to flush the buffer manually by doing the following: std::cout.
You can fix undefined reference in C++ by investigating the linker error messages and then providing the missing definition for the given symbols. Note that not all linker errors are undefined references, and the same programmer error does not cause all undefined reference errors.
So when we try to assign it a value in the main function, the linker doesn't find the symbol and may result in an “unresolved external symbol” or “undefined reference”. The way to fix this error is to explicitly scope the variable using '::' outside the main before using it.
Compile the program with:
g++ -Wall -Wextra -Werror -c main.cpp -o main.o
^^^^^^^^^^^^^^^^^^^^ <- For listing all warnings when your code is compiled.
as cout
is present in the C++ standard library, which would need explicit linking with -lstdc++
when using gcc
; g++
links the standard library by default.
With gcc
, (g++
should be preferred over gcc
)
gcc main.cpp -lstdc++ -o main.o
Yes, using g++
command worked for me:
g++ my_source_code.cpp
Assuming code.cpp
is the source code, the following will not throw errors:
make code
./code
Here the first command compiles the code and creates an executable with the same name, and the second command runs it. There is no need to specify g++
keyword in this case.
If you're working with a makefile and you ended up here like me, then this is probably what you're looking or:
If you're using a makefile, then you need to change cc
as shown below
my_executable : main.o
cc -o my_executable main.o
to
CC = g++
my_executable : main.o
$(CC) -o my_executable main.o
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With