Multiple functions (one version being inline and other beingnon-inline)

R

Rahul

Hi Everyone,

I have the following code,

file1.cpp
---------

#include <cstdio>

inline int sample1()
{
printf("1::sample1\n");
return(0);
}

int main()
{
sample1();
return(0);
}


file2.cpp
---------

#include <cstdio>

int sample1()
{
printf("2::sample1\n");
return(0);
}


when i build both the files and exeucte, i get the following output,

2::sample1


I expected a linker error, as file2.o is exporting sample1 which is
already available in file1.o... What does the standard indicate for
such scenarios?

Thanks in advance !!!
 
M

Marcel Müller

Rahul said:
I expected a linker error, as file2.o is exporting sample1 which is
already available in file1.o... What does the standard indicate for
such scenarios?

You must not define the same object twice in a different way. Otherwise
- as you might guess - undefined behaviour. (Look for the ODR.)


Marcel
 
N

nurxb01

I dont have knowledge of what standard says but I tried this with g++
2.95.3 and g++ is doing is
1] Keeps the sample1 funcion in file1.cpp as weak symbole in the
object file ( Probably because you have made it inline )
2] sample1 funcion in the file2.cpp is treated as Global symbol.

So when you link this two object modules the Global symbole gets
priority over Weak Symbol and you dont get any linker errors.

If you remove inline in sample1 funcion form file1.cpp, you should get
linker error.
 
J

James Kanze

I have the following code,

#include <cstdio>

inline int sample1()
{
printf("1::sample1\n");
return(0);
}
int main()
{
sample1();
return(0);
}

#include <cstdio>
int sample1()
{
printf("2::sample1\n");
return(0);
}
when i build both the files and exeucte, i get the following output,

I expected a linker error, as file2.o is exporting sample1
which is already available in file1.o... What does the
standard indicate for such scenarios?

It's undefined behavior, so anything the compiler does with it
is correct. §7.1.2/4: "If a function with external linkage is
declared inline in one translation unit, it shall be declared
inline in all translation units in which it appears; no
diagnostic is required."
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top