-2

i have code:

main.cpp

#include <iostream>
#include "add.h"
#include "var.h"

using namespace std;

int main() {
    std::cout << width << height << std::endl;
    show();
    return 0;
}

add.cpp

#include <iostream>
#include "add.h"
#include "var.h"

int add(int x, int y) {
    return x + y;
}

int show() {
    std::cout << width << height << std::endl;
    return 0;
}

add.h

#pragma once

int add(int x, int y);
int show();

var.cpp

#include "var.h"

int width = 1024, height = 768;

var.h

#pragma once

int width, height;

i need to include var.h in main.cpp and add.cpp to use variables in those files, but when i start compiling my program, i get an error: C2086 int width redefinition file var.cpp line 3, C2086 int height redefinition file var.cpp line 3

3
  • 4
    Use extern Commented Jun 1 at 16:08
  • 1
    @ildjarn inline since C++17. Commented Jun 1 at 16:16
  • 1
    Side note: nothing in this code needs the extra stuff that std::endl does. Use '\n' to end a line unless you have a good reason not to. Commented Jun 1 at 18:17

1 Answer 1

2

Things in include files should not generate code or object definitions.

int width = 1024, height = 768;

generates memory objects.

This should be in your .cpp file, not in an include file. (And must be in exactly one cpp file.)

The include file should look like

extern int width, height;

which generates declarations, not definitions.

Sign up to request clarification or add additional context in comments.

3 Comments

This should be in your .cpp file, not in an include file. They are in the OP's cpp file
In most cases, you'll just want to put something like constexpr int width = xxx; into your header. That way, the compiler will just use that as a constant instead of storing it separately.
and how to declare const variables and arrays in header file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.