Linux下__attribute__((aligned(n)))的使用
關鍵字__attribute__允許你在定義struct、union、變量等類型時指定特殊屬性。此關鍵字后面是跟著雙括號括起來的屬性說明。__attribute__不屬于標準C語言,它是GCC對C語言的一個擴展用法。
你可以在其關鍵字之前和之后使用"__"指定這些屬性中的一個,這樣允許你在頭文件中使用這些屬性,而不必擔心可能的同名宏。例如你可以使用__aligned__代替aligned。
??????? __attribute__((aligned(n))):此屬性指定了指定類型的變量的最小對齊(以字節為單位)。如果結構中有成員的長度大于n,則按照最大成員的長度來對齊。
注意:對齊屬性的有效性會受到鏈接器(linker)固有限制的限制,即如果你的鏈接器僅僅支持8字節對齊,即使你指定16字節對齊,那么它也僅僅提供8字節對齊。
?__attribute__((packed)):此屬性取消在編譯過程中的優化對齊。
關于C++內存對齊介紹可以參考: https://blog.csdn.net/fengbingchun/article/details/81270326
?以下是測試代碼(sample_attribute_aligned.cpp):
#include <iostream>int main() {struct S1 {short f[3];};struct S2 {short f[3];} __attribute__((aligned(64)));struct S5 {short f[40];} __attribute__((aligned(64)));fprintf(stdout, "S1 size: %d, S2 size: %d, S5 size: %d\n",sizeof(struct S1), sizeof(struct S2), sizeof(struct S5)); // 6, 64, 128typedef int more_aligned_int __attribute__((aligned(16)));fprintf(stdout, "aligned: %d, %d\n", alignof(int), alignof(more_aligned_int)); // 4, 16struct S3 {more_aligned_int f;};struct S4 {int f;};fprintf(stdout, "S3 size: %d, S4 size: %d\n", sizeof(struct S3), sizeof(struct S4)); // 16, 4int arr[2] __attribute__((aligned(16))) = {1, 2};fprintf(stdout, "arr size: %d, arr aligned: %d\n", sizeof(arr), alignof(arr)); // 8, 16struct S6 {more_aligned_int f;} __attribute__((packed));fprintf(stdout, "S6 size: %d\n", sizeof(struct S6)); // 4char c __attribute__((aligned(16))) = 'a';fprintf(stdout, "c size: %d, aligned: %d\n", sizeof(c), alignof(c)); // 1, 16struct S7 {double f;} __attribute__((aligned(4)));fprintf(stdout, "S7 size: %d, algined: %d\n", sizeof(struct S7), alignof(struct S7)); // 8, 8struct S8 {double f;} __attribute__((__aligned__(32)));fprintf(stdout, "S8 size: %d, algined: %d\n", sizeof(struct S8), alignof(struct S8)); // 32, 32return 0; }CMakeLists.txt文件內容如下:
PROJECT(samples_cplusplus) CMAKE_MINIMUM_REQUIRED(VERSION 3.0)# 支持C++11 SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -Wall -O2 -std=c11") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -Wall -O2 -std=c++11")INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR})FILE(GLOB samples ${PROJECT_SOURCE_DIR}/*.cpp)FOREACH (sample ${samples})STRING(REGEX MATCH "[^/]+$" sample_file ${sample})STRING(REPLACE ".cpp" "" sample_basename ${sample_file})ADD_EXECUTABLE(test_${sample_basename} ${sample})TARGET_LINK_LIBRARIES(test_${sample_basename} pthread) ENDFOREACH()build.sh腳本內容如下:
#! /bin/bashreal_path=$(realpath $0) dir_name=`dirname "${real_path}"` echo "real_path: ${real_path}, dir_name: ${dir_name}"new_dir_name=${dir_name}/build mkdir -p ${new_dir_name} cd ${new_dir_name} cmake .. makecd -編譯及測試方法如下:首先執行build.sh,然后再執行./build/test_sample_attribute_aligned即可。
GitHub: https://github.com/fengbingchun/Linux_Code_Test?
總結
以上是生活随笔為你收集整理的Linux下__attribute__((aligned(n)))的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FPGA布局及资源优化
- 下一篇: css中的容器坍塌问题