Book exersice: puts without include

Hello Comunity,

I am following a C++ Book; In one exercice, the Author ask over how to use the "puts()" call without its header;

I think that could be some relationed with "extern", but I'm not sure. I tried the next code but I have linker problems.

1
2
3
4
5
6
extern int puts(const char *str);

int main() {
	puts("Hello World without #include <cstdio>");
	return 0;
}


(When I compile, obtain: Warning: undefined reference to "puts (char const *)")

Please, somebody so kind to help me? Thanks in advance.
Last edited on
1
2
3
4
5
6
int puts(const char *str);

int main() {
	puts("Hello World without #include <cstdio>");
	return 0;
}
That is possible because the standard library is automatically linked, so you only need a valid prototype, correct? (Wouldn't work if a global object like std::cout is required)
Last edited on
$ g++ -c foo.cpp
$ nm foo.o
U _Z4putsPKc
c++ allow for function overload, so the compiler decorate the name to distinguish them
to avoid that you may use extern "C"
https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c
> I am following a C++ Book; In one exercice, the Author ask over how to use the "puts()" call without its header;

As far as C++ is concerned, there is no portable, standard way to this.

The entities in the C++ standard library are defined in headers, whose contents are made available to a translation unit when it contains the appropriate #include preprocessing directive.
http://eel.is/c++draft/using.headers

and
Whether a name from the C standard library declared with external linkage has extern "C" or extern "C++" linkage is implementation-defined. It is recommended that an implementation use extern "C++" linkage for this purpose.

Footnote: The only reliable way to declare an object or function signature from the C standard library is by including the header that declares it, notwithstanding the latitude granted in 7.1.4 of the C Standard.
http://eel.is/c++draft/using.linkage
Thank you very much to all.

Like ne555 said, has worked so:
1
2
3
4
5
6
7
8
9
10
11
extern "C"
{
int puts(const char *str);
}



int main() {
	puts("Hello World without Puts");
	return 0;
}


Thank you very much the rest for the theory
Topic archived. No new replies allowed.