2

This is a minimal example to reproduce a linker error from a program that worked in C but failed when compiling with C++ (gcc/g++ 8.1.0). I already know how to solve it using extern, what i want to find out is why it results in a linker error only in C++:

main.c

#include <stdio.h>

int var; //a definition in C++, declaration in C?

int main()
{
printf("%i\n", var);
return 0;
}

sec.c

int var = 10;

Just so i haven't misunderstood the terms:

declaration: allocating memory for a variable

definition: declaring and assigning it a meaningful value

This will compile with no complaints in C, but throw a multiple definition error in C++.

My running theory is that this is because C++ considers int var; a definition while C only considers it a declaration (maybe by assuming extern in main.c) this is only an assumption through experimentation (and i don't think it's right), i want to find out how it actually functions according to documentation.

I couldn't tell from the sources i looked at how exactly it interprets int var; between the two languages.

There are two supposed definitions of var, why does it compile in C but not C++?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Africa
  • 21
  • 1
  • I believe it's not legal in C either but earlier versions of gcc allowed it. https://stackoverflow.com/a/69908511/920069 – Retired Ninja Oct 20 '22 at 00:29
  • sidenote: excluding sec.c and explicitly declaring `extern int var;` in C will result in a linker error (as it should), throwing more doubt to the idea that `int var` would only be a declaration. – Africa Oct 20 '22 at 00:32
  • This is a difference between the two languages. In C var has external linkage, in C++ it has no linkage. See C17 6.2.2¶5 and C++17 [basic.link]. – Miles Budnek Oct 20 '22 at 00:40
  • @MilesBudnek: In C++, it has external linkage. Per C++ 2020 draft N4849 [basic.scope.namespace] 4, it is in the global namespace scope. Per [basic.link] 5, a name having namespace scope and not given linkage above (in paragraph 4) and that is the name of a variable, not enclosed in a namespace with internal linkage, and not attached to a name module, has external linkage. – Eric Postpischil Oct 20 '22 at 09:35
  • 1
    @RetiredNinja: It is legal in C, as there is no constraint against it. The behavior is not defined by the C standard. It was not defined because there were different practices by different C implementations, and the C committee chose not to codify them, so the reason it is undefined is in fact to allow different uses of it. – Eric Postpischil Oct 20 '22 at 09:36

0 Answers0