Problem with c/c++ linking under MinGW

Started by
2 comments, last by ursus 17 years, 10 months ago
Programmers, As always I must be missing something or some detail slips my attention. Here is the scenario, 3 files: main.c

#include "main.h"

main()
{
	assign();
	printf("Value: %d",var);
}

main.h

#include <stdio.h>

int var;

void assign();


test.c

#include "main.h"

void assign()
{
	var=5;
}

Quick, simple and pointles but this is just to ilustrate what I'm getting at. To compile the files I use MinGW: gcc -c -o main.o main.cpp gcc -c -o test.o test.cpp gcc -o test.exe main.o test.o and all above works perfectly. The problem appears when I change filenames to: main.cpp main.h test.h and try to compile the program with the same commands. When I do that I keep getting error: multiple definition of `var' and information that it was first defined in main.cpp I understand the header was compiled more than once so I tried surrounding the main.h file with: #ifndef MAIN_H #define MAIN_H . . . #endif but that doesn't help. What am I doing worng? Many thanks in advance
Advertisement
If I'm understanding what you're trying to say, and not what you've actually said, the problem is that C and C++ have different rules about global variable declarations and linkage, which is giving the difference in behavior that you're seeing. To properly declare a global variable in a header, you need to declare it as extern in the header file. Then in one source file, you need to define it at namespace scope (not inside a function or class). So in your main.h, you would have extern int var; and then in either main.cpp or text.cpp put int var;. For more details see this article.
Header files should not contain function or variable definitions.

In your example, "int var;" is a definition. What you want to do is make the fact that there is an int called var available. To do this use the keyword "extern".

This should compile:

// main.c#include "main.h"int main(){	assign();	printf("Value: %d",var);}// main.h#include <stdio.h>extern int var;void assign();// test.c#include "main.h"int var = 0;void assign(){	var=5;}


One thing though, I would have named main.h test.h as main.h contains the function and variable declarations for test.c which isn't intuitive.
Thank you for your help.

I guess I need some reading on this. I've been mostly using pure C so far and things seemed to be working fine.

This topic is closed to new replies.

Advertisement