Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this C code compile in Codeblocks, but not in Visual Studio?

When I try to compile the following C code on Visual Studio 2017 with default C/C++ settings:

#include <stdio.h>
#include <stdlib.h>


/* function declaration */
/*Line 6*/ int max(int num1, int num2, int num3); 

int main() {

/* local variable definition */
int a = 100;
int b = 200;
int c = 400;
int ret;

/* calling a function to get max value */
ret = max(a, b, c);
printf("Max value is : %d\n", ret);
return 0;
}

/* function returning the max between two numbers */
/*Line 25*/ int max(int num1, int num2, int num3) {

/* local variable declaration */
int result;

if (num1 > num2)
result = num1;
else
result = num3;
return result;
}

I get the error(s):

Expected an Identifier: Line(s) 6,25

Expected a ";": Line(s) 25

Intellisense highlights those lines and wont let me run the code. Yet in Codeblocks (Using the default GNU GCC compiler, from mingW) this EXACT code compiles just fine. What is causing this?

Multiple sources have told me that its not due to Codeblocks using GCC compiler and Visual Studio using "cl" compiler by default.

The same sources have told me that it is also not due to the possibility of each IDE compiling the code using different C standards.

I have named the the file extension as ".c" and I get these errors

If I try to compile the code as c++(or as a ".c++" file it works, but that's not what I want. I want C.

I would prefer to use Visual Studio over Codeblocks due to its sleek look and menu layout. I also prefer the Visual Studio debugger.

What steps can I take to successfully compile this simple code on Visual Studio 2017?

like image 733
Chris Avatar asked Jun 29 '26 09:06

Chris


1 Answers

Microsoft has a notoriously defined max macro. If the macro definition is pulled into your source for whatever reason, token substitution will wreak havoc. The result of that I'd wager is what you are seeing. Mostly because by your own admission, it happens only in Visual Studio.

The solution (and test for it) is fairly simple. One of these should "fix" your code:

  1. Rename max to something else, like my_max.
  2. Before including any headers, add #define NOMINMAX to suppress the definition of the macros in any included MS headers.

Beyond that you are gonna have to tinker with your project settings and see what may be improperly set. This is not a macro that should be automatically added in a simple console project.

like image 199
StoryTeller - Unslander Monica Avatar answered Jun 30 '26 23:06

StoryTeller - Unslander Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!