clang-format how to ignore extern C? - clang-format

This is my current sample code
#ifdef __cplusplus
extern "C"
{
#endif
typedef enum
{
BUY = 1,
SELL = 2
} OrderAction_e;
#ifdef __cplusplus
}
#endif
After I run the clang format it is changing as below.
#ifdef __cplusplus
extern "C"
{
#endif
typedef enum
{
BUY = 1,
SELL = 2
} OrderAction_e;
#ifdef __cplusplus
}
#endif
It is adding an additional two spaces for all my functions and typedefs.
Is there an option which I can use to ignore the extern C braces so that, my code looks unchanged like the first version of code I pasted above.
Following is the clang version used in my company
LLVM (http://llvm.org/):
LLVM version 3.4.2

If you were using a later version of clang-format, you could get very close. But with 3.4.2, I don't think so.
With version 6.0.0, you can get very close, but it seems to be necessary to put the brace on the same line as the extern "C" in order to disable the indentation of the extern "C" section. Doing this requires using the Custom setting for BreakBeforeBraces. This behavior of disabling indenting the extern "C" block doesn't appear to be documented anywhere, but it does work for me.
Try modifying your .clang-format file to contain this:
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterEnum: true # <-- You need this
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: false # <-- And this
BeforeCatch: true
BeforeElse: true
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: false
BreakBeforeBraces: Custom # <-- And this
Note that there are a bunch of options there which you can leave however you normally set them. Only the values of AfterEnum, AfterExternBlock, and BreakBeforeBraces matter for this. See the documentation for more details about these settings.
If you don't already have a .clang-format file, you would start by doing clang-format -dump-config > .clang-format and then edit the file.

Related

can I add extra flags to meson ```compiles``` test?

I want to use the ret variable to check, whether my cpu supports avx2:
ret = cc.compiles('''
#include <immintrin.h>
int main() {
__m256i m = _mm256_set1_epi32(17);
return sizeof(__mm256_srli_epi32(m 8);
}
''')
but I need to add somehow the compilation flag -mavx2.
Is that possible?
I read that in 2019 it wasn't, but maybe it has changed?
The badly documented args keyword is what you want:
cc.compiles(..., args : [...])

Clang-format struct initialization - indent with two spaces?

I'm trying to format a C file with clang-format. I want indentations to be two space characters, which mostly works except for in global variable struct initialization. For this, it continues to produce lines which are indented with four spaces.
Here is my .clang-format file
BasedOnStyle: LLVM
ColumnLimit: '80'
IndentWidth: '2'
clang-format produces this surprising output
typedef struct {
int x;
} foo;
static foo bar{
1, // This line is being indented with 4 spaces!
};
And this is what I'd expect the file to look like:
typedef struct {
int x;
} foo;
static foo bar{
1, // This line is being indented with 2 spaces!
};
I've tried using a few different values for ConstructorInitializerIndentWidth, but that field doesn't appear to affect this pattern.
Is there a setting that I could provide to get this behavior?
Try ContinuationIndentWidth: 2. That worked for me, when I had that problem.

Determine target name during compilation

I have several targets and depending on them I need to import headers. I can do this by defining some preprocessor value and then check it with #ifdef, but I'm wondering, if there any way to do something like:
#if TARGET_NAME = "FirstTarget"
#import "SomeHeader.h"
#endif
u can use like below for example,
//Your current target's are defined
#define FIRST_TARGET "FirstTarget"
#define SECOND_TARGET "SecondTarget"
#define THIRD_TARGET "ThirdTarget"
//set which target u want to run
#define TARGET_NAME FIRST_TARGET //SECOND_TARGET //THIRD_TARGET
//use like below
#if (TARGET_NAME == FIRST_TARGET) //or u can directly specify name instead of defining at the beginning
#import "SomeHeader.h"
//other headers
#elif (TARGET_NAME == SECOND_TARGET)
//header to be in second target
#elif (TARGET_NAME == THIRD_TARGET)
// other header
#endif
Edit:
i got it, it gives error because macros doesn't compare variable length values, for more details see this hear .
so in order to work u can change it like below,
//Your current target's are defined, instead of strings give some constant values
#define FIRST_TARGET 1//#"FirstTarget"
#define SECOND_TARGET 2//#"SecondTarget"
#define THIRD_TARGET 3//#"ThirdTarget"
//set which target u want to run
#define TARGET_NAME FIRST_TARGET //SECOND_TARGET //THIRD_TARGET
//use like below
#if TARGET_NAME == FIRST_TARGET
#import "SomeHeader.h"
//other headers
#elif (TARGET_NAME == SECOND_TARGET)
//header to be in second target
#elif (TARGET_NAME == THIRD_TARGET)
// other header
#endif

clang-format BinPackArguments not working as expected

clang-format has 2 options called BinPackParameters and
BinPackArguments. They seem to control how function declarations and function calls are indented.
BinPackParameters seems to provide the expected result for a function declaration but BinPackArguments does not seem to work as one would expect for a function call.
Here is a simple test file:
#include <stdbool.h>
void function_with_a_huge_name_that_should_just_not_be(unsigned int a, char *b, unsigned int c, unsigned int d, unsigned int e)
{
return;
}
int main()
{
function_with_a_huge_name_that_should_just_not_be(13, "bb", 1234234, 4324324, 2355345);
}
And this is how it is formatted:
#include <stdbool.h>
void function_with_a_huge_name_that_should_just_not_be(unsigned int a,
char *b,
unsigned int c,
unsigned int d,
unsigned int e)
{
return;
}
int main()
{
function_with_a_huge_name_that_should_just_not_be(
13, "bb", 1234234, 4324324, 2355345);
}
My .clang-format file is as follows:
---
AccessModifierOffset: -2
AlignAfterOpenBracket: false
AlignEscapedNewlinesLeft: false
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
AlwaysBreakAfterDefinitionReturnType: false
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackParameters: false
BinPackArguments: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Linux
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
IndentCaseLabels: false
IndentWidth: 4
IndentWrappedFunctionNames: false
IndentFunctionDeclarationAfterType: false
KeepEmptyLinesAtTheStartOfBlocks: false
Language: Cpp
MaxEmptyLinesToKeep: 2
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakString: 1000
PenaltyBreakFirstLessLess: 120
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
TabWidth: 4
UseTab: Never
My clang-format version is: 3.6.0 (tags/RELEASE_360/final)
With both BinPackParameters and BinPackArguments being false I would have expected to get the same indentation for the function call as I am getting for the function declaration.
Any idea what I am doing wrong?
I don't think you are doing anything wrong. What happens is that clang-format realizes that the line where you are calling the function is longer than your column limit (80 chars in your settings). Your AlignAfterOpenBracket is set to false, so clang-format places the arguments on a new line (Note that AlignAfterOpenBracket has gained additional possibilities in later versions of clang-format).
You have set both BinPack... settings to false, however there is an additional setting that controls the function declaration vs the function call, AllowAllParametersOfDeclarationOnNextLine (set to false in your example). For the function declaration, this will cause all parameters to be on separate lines if they do not fit on the same line as the function name. For the function call there is no corresponding setting.
In your case, the arguments that you give to the function are placed on the next line after the function name. The length of the second line is < 80, so clang-format does not do anything more with it. If the arguments line would have been longer than your column limit, clang-format would have placed them on separate lines.
So the answer is that as of version 3.9, there is no way to configure clang-format to place each argument on a separate line if they fit on one line.
Try to set ColumnLimit to 0. It looks like this option "overrides" or has a higher priority over BinPackParameters and BinPackArguments options.
BinPack* options set to false will force parameters/arguments to be either all on one line or each on separate line. Both cases are allowed, but not mixing, eg. two parameters on one line and the rest on another line is not allowed.
clang-format seems to choose all-on-one-line vs. each-on-separate-line format individually for each case.

NS_OPTIONS Bitmask Autogeneration

I have a large enum (for the sake of transparency 63 values), and I am now creating a NS_Options bitflag based on that enum. Is there a way that I can write this so that it will be flexible?
The main concerns I have with hardcoding it are:
If I add/remove an enum, I will have to manually add/remove it in my bitflag.
There is a lot of typing to generate these.
My .h file is getting intensely long (because I like to use whitespace and adequate comments)
The only solution I've come up with thus far is:
#define FlagForEnum(enum) 1 << enum
typedef NS_ENUM(NSInteger, ExampleEnum)
{
Value1,
Value2,
...
ValueN
}
typedef NS_OPTIONS(NSNumber, ExampleEnumFlags)
{
Value1Flag = FlagForEnum(Value1),
Value2Flag = FlagForEnum(Value2),
...
ValueNFlag = FlagForEnum(ValueN)
}
This is a barely adequate solution when I remove an enum (at least I get a compile error), and if the enum ordering gets changed, the flags' bitshifted position changes too (not that it truly matters, but it seems comforting). But it doesn't solve the 'this-is-a-lot-of-typing' problem, or the 'what-if-I-forget-to-add-a-flag' problem.
You can use a technique called X Macro
#define VALUES \
VALUE_LINE(Value1) \
VALUE_LINE(Value2) \
VALUE_LINE(Value3)
typedef NS_ENUM(NSUInteger, ExampleEnum)
{
#define VALUE_LINE(x) x,
VALUES
#undef VALUE_LINE
}
typedef NS_OPTIONS(NSUInteger, ExampleEnumFlags)
{
#define VALUE_LINE(x) x##Flag = 1 << x,
VALUES
#undef VALUE_LINE
}
Here is a slightly better (in terms of less typing) preprocessor #define solution. Although this still isn't as elegant as I'd like.
#define BitShift(ENUM_ATTRIBUTE) (1 << ENUM_ATTRIBUTE)
#define CreateEnumFlag(ENUM_ATTRIBUTE) ENUM_ATTRIBUTE##Flag = BitShift(ENUM_ATTRIBUTE)
typedef NS_ENUM(NSUInteger, ExampleEnum)
{
Value1,
Value2,
...
ValueN
}
typedef NS_Options(NSUInteger, ExampleEnumFlags)
{
CreateEnumFlag(Value1),
CreateEnumFlag(Value2),
...
CreateEnumFlag(ValueN)
}
This will create flags of the form Value1Flag, Value2Flag, ..., ValueNFlag.

Resources